code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : List[str] = [randint(-1000, 1000 ) for i in range(10 )] _SCREAMING_SNAKE_CASE : Union[str, Any] = randint(-5000, 5000 ) return (arr, r) UpperCamelCase__ =make_dataset() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): for triplet in permutations(__lowerCamelCase, 3 ): if sum(__lowerCamelCase ) == target: return tuple(sorted(__lowerCamelCase ) ) return (0, 0, 0) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): arr.sort() _SCREAMING_SNAKE_CASE : Optional[Any] = len(__lowerCamelCase ) for i in range(n - 1 ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : List[Any] = "\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n" _SCREAMING_SNAKE_CASE : Dict = "\ntriplet_sum1(*dataset)\n" _SCREAMING_SNAKE_CASE : Any = "\ntriplet_sum2(*dataset)\n" _SCREAMING_SNAKE_CASE : List[str] = repeat(setup=__lowerCamelCase, stmt=__lowerCamelCase, repeat=5, number=10000 ) _SCREAMING_SNAKE_CASE : Tuple = repeat(setup=__lowerCamelCase, stmt=__lowerCamelCase, repeat=5, number=10000 ) return (min(__lowerCamelCase ), min(__lowerCamelCase )) if __name__ == "__main__": from doctest import testmod testmod() UpperCamelCase__ =solution_times() print(f"The time for naive implementation is {times[0]}.") print(f"The time for optimized implementation is {times[1]}.")
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 1_2_8 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 2000.0 , __lowerCamelCase = 7_6_8 , __lowerCamelCase = 1_2 , __lowerCamelCase = 1_2 , __lowerCamelCase = 6_4 , __lowerCamelCase = 2_0_4_8 , __lowerCamelCase = 0.1 , ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential( nn.Linear(__lowerCamelCase , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : str = nn.Embedding(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() for lyr_num in range(__lowerCamelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Optional[int] = DecoderLayer(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) self.decoders.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(__lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : Optional[int] = torch.broadcast_to( torch.arange(__lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.position_encoding(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.continuous_inputs_projection(__lowerCamelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Any = self.dropout(__lowerCamelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Any = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : List[str] = [(x, self.encoder_decoder_mask(__lowerCamelCase , __lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : Tuple = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Optional[Any] = lyr( __lowerCamelCase , conditioning_emb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , )[0] _SCREAMING_SNAKE_CASE : int = self.decoder_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.spec_out(__lowerCamelCase ) return spec_out class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.layer[0]( __lowerCamelCase , conditioning_emb=__lowerCamelCase , attention_mask=__lowerCamelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : str = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : Tuple = self.layer[1]( __lowerCamelCase , key_value_states=__lowerCamelCase , attention_mask=__lowerCamelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer[-1](__lowerCamelCase , __lowerCamelCase ) return (hidden_states,) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: # pre_self_attention_layer_norm _SCREAMING_SNAKE_CASE : int = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Any = self.FiLMLayer(__lowerCamelCase , __lowerCamelCase ) # Self-attention block _SCREAMING_SNAKE_CASE : Optional[int] = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.attention( __lowerCamelCase , encoder_hidden_states=__lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.dropout(__lowerCamelCase ) return layer_output class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.film(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.DenseReluDense(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = NewGELUActivation() def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Dict = self.act(self.wi_a(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = self.wi_a(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Optional[int] = self.dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.wo(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.ones(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = eps def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : str = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> torch.Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(__lowerCamelCase , 3.0 )) )) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Any = nn.Linear(__lowerCamelCase , out_features * 2 , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.scale_bias(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = torch.chunk(__lowerCamelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE : Optional[int] = x * (1 + scale) + shift return x
325
1
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ =logging.get_logger(__name__) # General docstring UpperCamelCase__ ='RegNetConfig' # Base docstring UpperCamelCase__ ='facebook/regnet-y-040' UpperCamelCase__ =[1, 1088, 7, 7] # Image classification docstring UpperCamelCase__ ='facebook/regnet-y-040' UpperCamelCase__ ='tabby, tabby cat' UpperCamelCase__ =[ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 3 , __lowerCamelCase = 1 , __lowerCamelCase = 1 , __lowerCamelCase = "relu" , ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Convad( __lowerCamelCase , __lowerCamelCase , kernel_size=__lowerCamelCase , stride=__lowerCamelCase , padding=kernel_size // 2 , groups=__lowerCamelCase , bias=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Any = nn.BatchNormad(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = ACTaFN[activation] if activation is not None else nn.Identity() def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : List[Any] = self.convolution(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.normalization(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.activation(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : int = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) _SCREAMING_SNAKE_CASE : int = config.num_channels def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) _SCREAMING_SNAKE_CASE : List[Any] = self.embedder(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 2 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Convad(__lowerCamelCase , __lowerCamelCase , kernel_size=1 , stride=__lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = nn.BatchNormad(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Tensor: _SCREAMING_SNAKE_CASE : str = self.convolution(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.normalization(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : str = nn.AdaptiveAvgPoolad((1, 1) ) _SCREAMING_SNAKE_CASE : Tuple = nn.Sequential( nn.Convad(__lowerCamelCase , __lowerCamelCase , kernel_size=1 ) , nn.ReLU() , nn.Convad(__lowerCamelCase , __lowerCamelCase , kernel_size=1 ) , nn.Sigmoid() , ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: # b c h w -> b c 1 1 _SCREAMING_SNAKE_CASE : str = self.pooler(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_state * attention return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 1 ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = in_channels != out_channels or stride != 1 _SCREAMING_SNAKE_CASE : str = max(1 , out_channels // config.groups_width ) _SCREAMING_SNAKE_CASE : Dict = ( RegNetShortCut(__lowerCamelCase , __lowerCamelCase , stride=__lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) _SCREAMING_SNAKE_CASE : Tuple = nn.Sequential( RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , stride=__lowerCamelCase , groups=__lowerCamelCase , activation=config.hidden_act ) , RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , kernel_size=1 , activation=__lowerCamelCase ) , ) _SCREAMING_SNAKE_CASE : Dict = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Dict = hidden_state _SCREAMING_SNAKE_CASE : Tuple = self.layer(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.shortcut(__lowerCamelCase ) hidden_state += residual _SCREAMING_SNAKE_CASE : int = self.activation(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 1 ) -> Optional[int]: super().__init__() _SCREAMING_SNAKE_CASE : Any = in_channels != out_channels or stride != 1 _SCREAMING_SNAKE_CASE : Optional[Any] = max(1 , out_channels // config.groups_width ) _SCREAMING_SNAKE_CASE : int = ( RegNetShortCut(__lowerCamelCase , __lowerCamelCase , stride=__lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) _SCREAMING_SNAKE_CASE : str = nn.Sequential( RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , stride=__lowerCamelCase , groups=__lowerCamelCase , activation=config.hidden_act ) , RegNetSELayer(__lowerCamelCase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(__lowerCamelCase , __lowerCamelCase , kernel_size=1 , activation=__lowerCamelCase ) , ) _SCREAMING_SNAKE_CASE : str = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : Any = hidden_state _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.shortcut(__lowerCamelCase ) hidden_state += residual _SCREAMING_SNAKE_CASE : Union[str, Any] = self.activation(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = 2 , __lowerCamelCase = 2 , ) -> Tuple: super().__init__() _SCREAMING_SNAKE_CASE : str = RegNetXLayer if config.layer_type == "x" else RegNetYLayer _SCREAMING_SNAKE_CASE : str = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , stride=__lowerCamelCase , ) , *[layer(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) for _ in range(depth - 1 )] , ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.layers(__lowerCamelCase ) return hidden_state class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase ) -> Tuple: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( __lowerCamelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) _SCREAMING_SNAKE_CASE : Optional[int] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__lowerCamelCase , config.depths[1:] ): self.stages.append(RegNetStage(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , depth=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = False , __lowerCamelCase = True ) -> BaseModelOutputWithNoAttention: _SCREAMING_SNAKE_CASE : str = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _SCREAMING_SNAKE_CASE : Tuple = hidden_states + (hidden_state,) _SCREAMING_SNAKE_CASE : List[Any] = stage_module(__lowerCamelCase ) if output_hidden_states: _SCREAMING_SNAKE_CASE : Dict = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase , hidden_states=__lowerCamelCase ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = RegNetConfig __snake_case = 'regnet' __snake_case = 'pixel_values' __snake_case = True def UpperCamelCase_ ( self , __lowerCamelCase ) -> Tuple: if isinstance(__lowerCamelCase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(__lowerCamelCase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=False ) -> Dict: if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = value UpperCamelCase__ =R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): 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' UpperCamelCase__ =R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , __lowercase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase ) -> Dict: super().__init__(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = config _SCREAMING_SNAKE_CASE : Union[str, Any] = RegNetEmbeddings(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = RegNetEncoder(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None ) -> BaseModelOutputWithPoolingAndNoAttention: _SCREAMING_SNAKE_CASE : str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE : Tuple = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE : Tuple = self.embedder(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.encoder( __lowerCamelCase , output_hidden_states=__lowerCamelCase , return_dict=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_outputs[0] _SCREAMING_SNAKE_CASE : Optional[Any] = self.pooler(__lowerCamelCase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase , pooler_output=__lowerCamelCase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , __lowercase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase ) -> Union[str, Any]: super().__init__(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = config.num_labels _SCREAMING_SNAKE_CASE : Any = RegNetModel(__lowerCamelCase ) # classification head _SCREAMING_SNAKE_CASE : Any = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , ) -> ImageClassifierOutputWithNoAttention: _SCREAMING_SNAKE_CASE : Any = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE : Tuple = self.regnet(__lowerCamelCase , output_hidden_states=__lowerCamelCase , return_dict=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = outputs.pooler_output if return_dict else outputs[1] _SCREAMING_SNAKE_CASE : Tuple = self.classifier(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE : List[Any] = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE : Dict = "single_label_classification" else: _SCREAMING_SNAKE_CASE : List[Any] = "multi_label_classification" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE : Union[str, Any] = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE : Tuple = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE : Optional[int] = loss_fct(__lowerCamelCase , __lowerCamelCase ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE : List[Any] = CrossEntropyLoss() _SCREAMING_SNAKE_CASE : Union[str, Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE : Tuple = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE : Any = loss_fct(__lowerCamelCase , __lowerCamelCase ) if not return_dict: _SCREAMING_SNAKE_CASE : Optional[int] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__lowerCamelCase , logits=__lowerCamelCase , hidden_states=outputs.hidden_states )
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowerCAmelCase__( __lowercase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , "tf_padding" ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , "depth_multiplier" ) ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=3 , __lowerCamelCase=3_2 , __lowerCamelCase=0.25 , __lowerCamelCase=8 , __lowerCamelCase=8 , __lowerCamelCase=6 , __lowerCamelCase=3_2 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase="relu6" , __lowerCamelCase=1_2_8_0 , __lowerCamelCase=0.1 , __lowerCamelCase=0.02 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=1_0 , __lowerCamelCase=None , ) -> int: _SCREAMING_SNAKE_CASE : Dict = parent _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : Any = image_size _SCREAMING_SNAKE_CASE : List[str] = depth_multiplier _SCREAMING_SNAKE_CASE : Tuple = depth_divisible_by _SCREAMING_SNAKE_CASE : Tuple = min_depth _SCREAMING_SNAKE_CASE : int = expand_ratio _SCREAMING_SNAKE_CASE : int = tf_padding _SCREAMING_SNAKE_CASE : List[str] = output_stride _SCREAMING_SNAKE_CASE : Union[str, Any] = first_layer_is_expansion _SCREAMING_SNAKE_CASE : Optional[int] = finegrained_output _SCREAMING_SNAKE_CASE : int = hidden_act _SCREAMING_SNAKE_CASE : List[str] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) _SCREAMING_SNAKE_CASE : Optional[Any] = classifier_dropout_prob _SCREAMING_SNAKE_CASE : int = use_labels _SCREAMING_SNAKE_CASE : str = is_training _SCREAMING_SNAKE_CASE : Dict = num_labels _SCREAMING_SNAKE_CASE : Any = initializer_range _SCREAMING_SNAKE_CASE : Dict = scope def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE : List[str] = None _SCREAMING_SNAKE_CASE : int = None if self.use_labels: _SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) _SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _SCREAMING_SNAKE_CASE : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self ) -> Optional[int]: return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__lowerCamelCase ) 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, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : str = self.num_labels _SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : Tuple = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Any = self.num_labels _SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : List[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __snake_case = ( { 'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification, 'image-segmentation': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Tuple = MobileNetVaModelTester(self ) _SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def UpperCamelCase_ ( self ) -> Union[str, Any]: pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def UpperCamelCase_ ( self ) -> int: pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def UpperCamelCase_ ( self ) -> Any: pass def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Dict = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: def check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[Any] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = outputs.hidden_states _SCREAMING_SNAKE_CASE : str = 1_6 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[str] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : int = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> List[Any]: for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self ) -> Tuple: return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[str] = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.default_image_processor _SCREAMING_SNAKE_CASE : List[str] = prepare_img() _SCREAMING_SNAKE_CASE : int = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__lowerCamelCase ) # verify the logits _SCREAMING_SNAKE_CASE : Optional[int] = torch.Size((1, 1_0_0_1) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([0.2445, -1.1993, 0.1905] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Tuple = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) _SCREAMING_SNAKE_CASE : Dict = model.to(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_img() _SCREAMING_SNAKE_CASE : Any = image_processor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits _SCREAMING_SNAKE_CASE : int = torch.Size((1, 2_1, 6_5, 6_5) ) self.assertEqual(logits.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = torch.tensor( [ [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] , device=__lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
325
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'timesformer' def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> List[str]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = qkv_bias _SCREAMING_SNAKE_CASE : Tuple = attention_type _SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate
325
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'mra' def __init__( self , __lowerCamelCase=5_0_2_6_5 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-5 , __lowerCamelCase="absolute" , __lowerCamelCase=4 , __lowerCamelCase="full" , __lowerCamelCase=0 , __lowerCamelCase=0 , __lowerCamelCase=1 , __lowerCamelCase=0 , __lowerCamelCase=2 , **__lowerCamelCase , ) -> int: super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size _SCREAMING_SNAKE_CASE : Dict = max_position_embeddings _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : str = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = intermediate_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act _SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range _SCREAMING_SNAKE_CASE : int = type_vocab_size _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = position_embedding_type _SCREAMING_SNAKE_CASE : str = block_per_row _SCREAMING_SNAKE_CASE : str = approx_mode _SCREAMING_SNAKE_CASE : Union[str, Any] = initial_prior_first_n_blocks _SCREAMING_SNAKE_CASE : List[Any] = initial_prior_diagonal_n_blocks
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="[CLS]" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<unk>" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<pad>" , __lowerCamelCase="[CLS]" , __lowerCamelCase="[MASK]" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _SCREAMING_SNAKE_CASE : List[Any] = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : str = keep_accents _SCREAMING_SNAKE_CASE : Optional[int] = vocab_file _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: if self.remove_space: _SCREAMING_SNAKE_CASE : List[str] = " ".join(inputs.strip().split() ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = inputs _SCREAMING_SNAKE_CASE : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: _SCREAMING_SNAKE_CASE : str = unicodedata.normalize("NFKD" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: _SCREAMING_SNAKE_CASE : Dict = outputs.lower() return outputs def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): _SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[1:] else: _SCREAMING_SNAKE_CASE : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[str] = "" _SCREAMING_SNAKE_CASE : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : List[Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCamelCase__ ={ 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xlm': ['XLMTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'XLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMForMultipleChoice', 'XLMForQuestionAnswering', 'XLMForQuestionAnsweringSimple', 'XLMForSequenceClassification', 'XLMForTokenClassification', 'XLMModel', 'XLMPreTrainedModel', 'XLMWithLMHeadModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMForMultipleChoice', 'TFXLMForQuestionAnsweringSimple', 'TFXLMForSequenceClassification', 'TFXLMForTokenClassification', 'TFXLMMainLayer', 'TFXLMModel', 'TFXLMPreTrainedModel', 'TFXLMWithLMHeadModel', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
1
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ (__lowerCamelCase = "laptop" ): _SCREAMING_SNAKE_CASE : Tuple = f"""https://www.amazon.in/laptop/s?k={product}""" _SCREAMING_SNAKE_CASE : List[Any] = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } _SCREAMING_SNAKE_CASE : Optional[int] = BeautifulSoup(requests.get(__lowerCamelCase, headers=__lowerCamelCase ).text ) # Initialize a Pandas dataframe with the column titles _SCREAMING_SNAKE_CASE : Optional[Any] = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div", attrs={"class": "s-result-item", "data-component-type": "s-search-result"}, ), soup.find_all("div", attrs={"class": "a-row a-size-base a-color-base"} ), ): try: _SCREAMING_SNAKE_CASE : Union[str, Any] = item.ha.text _SCREAMING_SNAKE_CASE : int = "https://www.amazon.in/" + item.ha.a["href"] _SCREAMING_SNAKE_CASE : Optional[Any] = item.find("span", attrs={"class": "a-offscreen"} ).text try: _SCREAMING_SNAKE_CASE : List[Any] = item.find("span", attrs={"class": "a-icon-alt"} ).text except AttributeError: _SCREAMING_SNAKE_CASE : Optional[Any] = "Not available" try: _SCREAMING_SNAKE_CASE : Tuple = ( "₹" + item.find( "span", attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: _SCREAMING_SNAKE_CASE : int = "" try: _SCREAMING_SNAKE_CASE : Optional[int] = float( ( ( float(product_mrp.strip("₹" ).replace(",", "" ) ) - float(product_price.strip("₹" ).replace(",", "" ) ) ) / float(product_mrp.strip("₹" ).replace(",", "" ) ) ) * 100 ) except ValueError: _SCREAMING_SNAKE_CASE : List[str] = float("nan" ) except AttributeError: pass _SCREAMING_SNAKE_CASE : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] _SCREAMING_SNAKE_CASE : Union[str, Any] = " " _SCREAMING_SNAKE_CASE : List[str] = " " data_frame.index += 1 return data_frame if __name__ == "__main__": UpperCamelCase__ ='headphones' get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv")
325
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
1
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = [False] * len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [-1] * len(__lowerCamelCase ) def dfs(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : Optional[int] = c for u in graph[v]: if not visited[u]: dfs(__lowerCamelCase, 1 - c ) for i in range(len(__lowerCamelCase ) ): if not visited[i]: dfs(__lowerCamelCase, 0 ) for i in range(len(__lowerCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph UpperCamelCase__ ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_encodec': [ 'ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EncodecConfig', ], 'feature_extraction_encodec': ['EncodecFeatureExtractor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST', 'EncodecModel', 'EncodecPreTrainedModel', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
1
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = RoFormerTokenizer __snake_case = RoFormerTokenizerFast __snake_case = True __snake_case = True def UpperCamelCase_ ( self ) -> List[Any]: super().setUp() def UpperCamelCase_ ( self , **__lowerCamelCase ) -> List[Any]: return self.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **__lowerCamelCase ) def UpperCamelCase_ ( self , **__lowerCamelCase ) -> int: return self.rust_tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Dict = "永和服装饰品有限公司,今天天气非常好" _SCREAMING_SNAKE_CASE : Any = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好" return input_text, output_text def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.get_chinese_input_output_texts() _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , output_text.split() ) _SCREAMING_SNAKE_CASE : List[str] = tokens + [tokenizer.unk_token] _SCREAMING_SNAKE_CASE : List[str] = [2_2_9_4_3, 2_1_3_3_2, 3_4_4_3_1, 4_5_9_0_4, 1_1_7, 3_0_6, 1_2_3_1, 1_2_3_1, 2_6_5_3, 3_3_9_9_4, 1_2_6_6, 1_0_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[int] = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self.get_chinese_input_output_texts() _SCREAMING_SNAKE_CASE : int = tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , output_text.split() ) _SCREAMING_SNAKE_CASE : Any = tokens + [tokenizer.unk_token] _SCREAMING_SNAKE_CASE : str = [2_2_9_4_3, 2_1_3_3_2, 3_4_4_3_1, 4_5_9_0_4, 1_1_7, 3_0_6, 1_2_3_1, 1_2_3_1, 2_6_5_3, 3_3_9_9_4, 1_2_6_6, 1_0_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[int]: pass def UpperCamelCase_ ( self ) -> Union[str, Any]: pass def UpperCamelCase_ ( self ) -> Any: pass
325
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = 1_3 _SCREAMING_SNAKE_CASE : List[str] = 7 _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : int = 9_9 _SCREAMING_SNAKE_CASE : str = 3_8_4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = 3_7 _SCREAMING_SNAKE_CASE : Union[str, Any] = "gelu" _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 _SCREAMING_SNAKE_CASE : Tuple = 1_6 _SCREAMING_SNAKE_CASE : Dict = 2 _SCREAMING_SNAKE_CASE : Any = 0.02 _SCREAMING_SNAKE_CASE : Any = 3 _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 1_2_8 _SCREAMING_SNAKE_CASE : Optional[int] = 2 _SCREAMING_SNAKE_CASE : int = 9 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = TFConvBertForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : str = TFConvBertForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_choices _SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = self.num_labels _SCREAMING_SNAKE_CASE : Tuple = TFConvBertForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : int = TFConvBertModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True if hasattr(__lowerCamelCase , "use_cache" ): _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = os.path.join(__lowerCamelCase , "saved_model" , "1" ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.models.load_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : List[Any] = outputs["encoder_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs["encoder_attentions"] else: _SCREAMING_SNAKE_CASE : List[str] = outputs["hidden_states"] _SCREAMING_SNAKE_CASE : Dict = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) _SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = [1, 6, 7_6_8] self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
325
1
from __future__ import annotations UpperCamelCase__ =10 def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = 1 _SCREAMING_SNAKE_CASE : str = max(__lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _SCREAMING_SNAKE_CASE : list[list] = [[] for _ in range(__lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _SCREAMING_SNAKE_CASE : str = int((i / placement) % RADIX ) buckets[tmp].append(__lowerCamelCase ) # put each buckets' contents into list_of_ints _SCREAMING_SNAKE_CASE : Dict = 0 for b in range(__lowerCamelCase ): for i in buckets[b]: _SCREAMING_SNAKE_CASE : Union[str, Any] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
325
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
1
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCamelCase__ =datasets.logging.get_logger(__name__) UpperCamelCase__ ='\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' UpperCamelCase__ ='\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' UpperCamelCase__ ='\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase=False, __lowerCamelCase=False, __lowerCamelCase=True, __lowerCamelCase=False, __lowerCamelCase="dummy_doc" ): _SCREAMING_SNAKE_CASE : Optional[int] = {doc: key_lines} _SCREAMING_SNAKE_CASE : List[str] = {doc: sys_lines} _SCREAMING_SNAKE_CASE : List[Any] = {} _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Tuple = 0 _SCREAMING_SNAKE_CASE : Tuple = 0 _SCREAMING_SNAKE_CASE : Dict = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = reader.get_doc_mentions(__lowerCamelCase, key_doc_lines[doc], __lowerCamelCase ) key_singletons_num += singletons_num if NP_only or min_span: _SCREAMING_SNAKE_CASE : List[Any] = reader.set_annotated_parse_trees(__lowerCamelCase, key_doc_lines[doc], __lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = reader.get_doc_mentions(__lowerCamelCase, sys_doc_lines[doc], __lowerCamelCase ) sys_singletons_num += singletons_num if NP_only or min_span: _SCREAMING_SNAKE_CASE : Tuple = reader.set_annotated_parse_trees(__lowerCamelCase, key_doc_lines[doc], __lowerCamelCase, __lowerCamelCase ) if remove_nested: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = reader.remove_nested_coref_mentions(__lowerCamelCase, __lowerCamelCase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = reader.remove_nested_coref_mentions(__lowerCamelCase, __lowerCamelCase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _SCREAMING_SNAKE_CASE : Optional[Any] = reader.get_mention_assignments(__lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = reader.get_mention_assignments(__lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " f"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}""" ) logger.info( "Number of resulting singleton clusters in the key " f"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}""" ) if not keep_singletons: logger.info( f"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """ "files, respectively" ) return doc_coref_infos def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = get_coref_infos(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = {} _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Tuple = 0 for name, metric in metrics: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = evaluator.evaluate_documents(__lowerCamelCase, __lowerCamelCase, beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f"""{name}/recall""": recall, f"""{name}/precision""": precision, f"""{name}/f1""": fa} ) logger.info( name.ljust(10 ), f"""Recall: {recall * 100:.2f}""", f""" Precision: {precision * 100:.2f}""", f""" F1: {fa * 100:.2f}""", ) if conll_subparts_num == 3: _SCREAMING_SNAKE_CASE : Optional[Any] = (conll / 3) * 100 logger.info(f"""CoNLL score: {conll:.2f}""" ) output_scores.update({"conll_score": conll} ) return output_scores def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _SCREAMING_SNAKE_CASE : Any = line.split()[5] if not parse_col == "-": _SCREAMING_SNAKE_CASE : Optional[Any] = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _SCREAMING_SNAKE_CASE : Dict = util.check_gold_parse_annotation(__lowerCamelCase ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _SCREAMING_SNAKE_CASE : List[str] = evaluate( key_lines=__lowerCamelCase , sys_lines=__lowerCamelCase , metrics=__lowerCamelCase , NP_only=__lowerCamelCase , remove_nested=__lowerCamelCase , keep_singletons=__lowerCamelCase , min_span=__lowerCamelCase , ) return score
325
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
1
from __future__ import annotations def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = 0.00 _SCREAMING_SNAKE_CASE : List[str] = 0 for resistor in resistors: if resistor <= 0: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""Resistor at index {index} has a negative or zero value!""" raise ValueError(__lowerCamelCase ) first_sum += 1 / float(__lowerCamelCase ) index += 1 return 1 / first_sum def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = 0.00 _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for resistor in resistors: sum_r += resistor if resistor < 0: _SCREAMING_SNAKE_CASE : Optional[int] = f"""Resistor at index {index} has a negative value!""" raise ValueError(__lowerCamelCase ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
325
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ =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). UpperCamelCase__ =[0, 25, 50] UpperCamelCase__ =[25, 50, 75] UpperCamelCase__ =fuzz.membership.trimf(X, abca) UpperCamelCase__ =fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCamelCase__ =np.ones(75) UpperCamelCase__ =np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCamelCase__ =fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCamelCase__ =young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCamelCase__ =young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCamelCase__ =fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCamelCase__ =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()
325
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, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['pixel_values'] def __init__( self , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = PIL.Image.BICUBIC , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = 1 / 2_5_5 , __lowerCamelCase = True , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = size if size is not None else {"height": 2_5_6, "width": 2_5_6} _SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4} _SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(__lowerCamelCase , param_name="crop_size" ) _SCREAMING_SNAKE_CASE : str = do_resize _SCREAMING_SNAKE_CASE : Optional[Any] = size _SCREAMING_SNAKE_CASE : str = resample _SCREAMING_SNAKE_CASE : Union[str, Any] = do_center_crop _SCREAMING_SNAKE_CASE : Dict = crop_size _SCREAMING_SNAKE_CASE : Tuple = do_rescale _SCREAMING_SNAKE_CASE : Dict = rescale_factor _SCREAMING_SNAKE_CASE : Optional[Any] = do_normalize _SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = PIL.Image.BICUBIC , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray: _SCREAMING_SNAKE_CASE : List[str] = get_size_dict(__lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return resize( __lowerCamelCase , size=(size["height"], size["width"]) , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray: _SCREAMING_SNAKE_CASE : List[str] = get_size_dict(__lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(__lowerCamelCase , size=(size["height"], size["width"]) , data_format=__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ) -> Tuple: return rescale(__lowerCamelCase , scale=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray: return normalize(__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = ChannelDimension.FIRST , **__lowerCamelCase , ) -> PIL.Image.Image: _SCREAMING_SNAKE_CASE : List[str] = do_resize if do_resize is not None else self.do_resize _SCREAMING_SNAKE_CASE : Optional[Any] = resample if resample is not None else self.resample _SCREAMING_SNAKE_CASE : str = do_center_crop if do_center_crop is not None else self.do_center_crop _SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale _SCREAMING_SNAKE_CASE : int = rescale_factor if rescale_factor is not None else self.rescale_factor _SCREAMING_SNAKE_CASE : List[str] = do_normalize if do_normalize is not None else self.do_normalize _SCREAMING_SNAKE_CASE : Tuple = image_mean if image_mean is not None else self.image_mean _SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else self.image_std _SCREAMING_SNAKE_CASE : List[str] = size if size is not None else self.size _SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size _SCREAMING_SNAKE_CASE : List[str] = get_size_dict(__lowerCamelCase , param_name="crop_size" ) _SCREAMING_SNAKE_CASE : Tuple = make_list_of_images(__lowerCamelCase ) if not valid_images(__lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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. _SCREAMING_SNAKE_CASE : int = [to_numpy_array(__lowerCamelCase ) for image in images] if do_resize: _SCREAMING_SNAKE_CASE : Dict = [self.resize(image=__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase ) for image in images] if do_center_crop: _SCREAMING_SNAKE_CASE : Dict = [self.center_crop(image=__lowerCamelCase , size=__lowerCamelCase ) for image in images] if do_rescale: _SCREAMING_SNAKE_CASE : Optional[int] = [self.rescale(image=__lowerCamelCase , scale=__lowerCamelCase ) for image in images] if do_normalize: _SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase ) for image in images] _SCREAMING_SNAKE_CASE : str = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images] _SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase )
325
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'openai/whisper-base' __snake_case = ( 'This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the ' 'transcribed text.' ) __snake_case = 'transcriber' __snake_case = WhisperProcessor __snake_case = WhisperForConditionalGeneration __snake_case = ['audio'] __snake_case = ['text'] def UpperCamelCase_ ( self , __lowerCamelCase ) -> Tuple: return self.pre_processor(__lowerCamelCase , return_tensors="pt" ).input_features def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.model.generate(inputs=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Union[str, Any]: return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
325
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lowerCamelCase, max_perimeter + 1 ): _SCREAMING_SNAKE_CASE : List[Any] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase__ (__lowerCamelCase = 1000 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = pythagorean_triple(__lowerCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
325
1
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 lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = LayoutLMTokenizer __snake_case = LayoutLMTokenizerFast __snake_case = True __snake_case = True def UpperCamelCase_ ( self ) -> Any: super().setUp() _SCREAMING_SNAKE_CASE : Dict = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self , **__lowerCamelCase ) -> List[Any]: return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = "UNwant\u00E9d,running" _SCREAMING_SNAKE_CASE : List[str] = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(__lowerCamelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [7, 4, 5, 1_0, 8, 9] ) def UpperCamelCase_ ( self ) -> Any: pass
325
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # ===== initialization ===== _SCREAMING_SNAKE_CASE : List[Any] = Mock() _SCREAMING_SNAKE_CASE : Optional[Any] = conn, Mock() _SCREAMING_SNAKE_CASE : Dict = iter([1, None] ) _SCREAMING_SNAKE_CASE : Optional[Any] = lambda __lowerCamelCase : next(__lowerCamelCase ) # ===== invoke ===== send_file(filename="mytext.txt", testing=__lowerCamelCase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
325
1
from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=[1, 1, 2] , __lowerCamelCase=1 , __lowerCamelCase=3_2 , __lowerCamelCase=4 , __lowerCamelCase=8 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu_new" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=0.0 , __lowerCamelCase=5_1_2 , __lowerCamelCase=3 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , __lowerCamelCase=False , ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size _SCREAMING_SNAKE_CASE : Optional[Any] = seq_length _SCREAMING_SNAKE_CASE : Any = is_training _SCREAMING_SNAKE_CASE : Optional[int] = use_input_mask _SCREAMING_SNAKE_CASE : List[str] = use_token_type_ids _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : str = vocab_size _SCREAMING_SNAKE_CASE : Tuple = block_sizes _SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers _SCREAMING_SNAKE_CASE : Tuple = d_model _SCREAMING_SNAKE_CASE : str = n_head _SCREAMING_SNAKE_CASE : str = d_head _SCREAMING_SNAKE_CASE : Optional[int] = d_inner _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act _SCREAMING_SNAKE_CASE : Any = hidden_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout _SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout _SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings _SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Tuple = num_labels _SCREAMING_SNAKE_CASE : int = num_choices _SCREAMING_SNAKE_CASE : Union[str, Any] = scope _SCREAMING_SNAKE_CASE : List[str] = initializer_std # Used in the tests to check the size of the first attention layer _SCREAMING_SNAKE_CASE : Dict = n_head # Used in the tests to check the size of the first hidden state _SCREAMING_SNAKE_CASE : Union[str, Any] = self.d_model # Used in the tests to check the number of output hidden states/attentions _SCREAMING_SNAKE_CASE : Union[str, Any] = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: _SCREAMING_SNAKE_CASE : Any = self.num_hidden_layers + 2 def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : str = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Any = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : int = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[str]: _SCREAMING_SNAKE_CASE : Tuple = TFFunnelModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : Optional[int] = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : Dict = TFFunnelModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Any = TFFunnelModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFFunnelBaseModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Dict = TFFunnelBaseModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : int = TFFunnelBaseModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Any: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFFunnelForPreTraining(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> str: _SCREAMING_SNAKE_CASE : Dict = TFFunnelForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Any = self.num_labels _SCREAMING_SNAKE_CASE : Any = TFFunnelForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Dict: _SCREAMING_SNAKE_CASE : List[str] = self.num_choices _SCREAMING_SNAKE_CASE : str = TFFunnelForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Any = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : int = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : Union[str, Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_labels _SCREAMING_SNAKE_CASE : Any = TFFunnelForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = TFFunnelForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : Dict = config_and_inputs _SCREAMING_SNAKE_CASE : Dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[str] = TFFunnelModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) @require_tf class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = TFFunnelModelTester(self , base=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase )
325
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['image_processor', 'tokenizer'] __snake_case = 'BlipImageProcessor' __snake_case = 'AutoTokenizer' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE : List[str] = qformer_tokenizer def __call__( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE : Any = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) encoding.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.qformer_tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : str = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE : List[Any] = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) encoding.update(__lowerCamelCase ) return encoding def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Union[str, Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> str: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> Any: if os.path.isfile(__lowerCamelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(__lowerCamelCase ) return super().save_pretrained(__lowerCamelCase , **__lowerCamelCase ) @classmethod def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(__lowerCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_arguments_from_pretrained(__lowerCamelCase , **__lowerCamelCase ) args.append(__lowerCamelCase ) return cls(*__lowerCamelCase )
325
1
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--user', type=str, default='ubuntu') parser.add_argument('--host', type=str, default='localhost') parser.add_argument('--key_path', type=str, default=None) parser.add_argument('--instance', type=str, default='V100:1') parser.add_argument('--provider', type=str, default='cheapest') parser.add_argument('--use_spot', type=bool, default=False) parser.add_argument('--example', type=str, default='pytorch/text-generation/run_generation.py') UpperCamelCase__ , UpperCamelCase__ =parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('Cannot specify both BYO and on-demand cluster args') UpperCamelCase__ =rh.cluster( name='rh-cluster', ips=[args.host], ssh_creds={'ssh_user': args.user, 'ssh_private_key': args.key_path} ) else: UpperCamelCase__ =rh.cluster( name='rh-cluster', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) UpperCamelCase__ =args.example.rsplit('/', 1)[0] # Set up remote environment cluster.install_packages(['pip:./']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"pip install -r transformers/examples/{example_dir}/requirements.txt"]) cluster.run(['pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}"]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
325
from maths.prime_check import is_prime def lowerCamelCase__ (__lowerCamelCase ): if not isinstance(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(__lowerCamelCase ) if is_prime(__lowerCamelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
325
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'transfo-xl-wt103': 'https://huggingface.co/transfo-xl-wt103/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'transfo-xl' __snake_case = ['mems'] __snake_case = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , __lowerCamelCase=2_6_7_7_3_5 , __lowerCamelCase=[2_0_0_0_0, 4_0_0_0_0, 2_0_0_0_0_0] , __lowerCamelCase=1_0_2_4 , __lowerCamelCase=1_0_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=6_4 , __lowerCamelCase=4_0_9_6 , __lowerCamelCase=4 , __lowerCamelCase=False , __lowerCamelCase=1_8 , __lowerCamelCase=1_6_0_0 , __lowerCamelCase=1_0_0_0 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=0 , __lowerCamelCase=-1 , __lowerCamelCase=True , __lowerCamelCase=0.1 , __lowerCamelCase=0.0 , __lowerCamelCase=True , __lowerCamelCase="normal" , __lowerCamelCase=0.01 , __lowerCamelCase=0.01 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-5 , __lowerCamelCase=0 , **__lowerCamelCase , ) -> Any: _SCREAMING_SNAKE_CASE : Tuple = vocab_size _SCREAMING_SNAKE_CASE : Dict = [] self.cutoffs.extend(__lowerCamelCase ) if proj_share_all_but_first: _SCREAMING_SNAKE_CASE : str = [False] + [True] * len(self.cutoffs ) else: _SCREAMING_SNAKE_CASE : Any = [False] + [False] * len(self.cutoffs ) _SCREAMING_SNAKE_CASE : int = d_model _SCREAMING_SNAKE_CASE : Union[str, Any] = d_embed _SCREAMING_SNAKE_CASE : List[Any] = d_head _SCREAMING_SNAKE_CASE : Union[str, Any] = d_inner _SCREAMING_SNAKE_CASE : str = div_val _SCREAMING_SNAKE_CASE : Union[str, Any] = pre_lnorm _SCREAMING_SNAKE_CASE : List[Any] = n_layer _SCREAMING_SNAKE_CASE : Optional[int] = n_head _SCREAMING_SNAKE_CASE : Optional[Any] = mem_len _SCREAMING_SNAKE_CASE : Optional[int] = same_length _SCREAMING_SNAKE_CASE : int = attn_type _SCREAMING_SNAKE_CASE : str = clamp_len _SCREAMING_SNAKE_CASE : Optional[int] = sample_softmax _SCREAMING_SNAKE_CASE : Optional[int] = adaptive _SCREAMING_SNAKE_CASE : List[str] = dropout _SCREAMING_SNAKE_CASE : Dict = dropatt _SCREAMING_SNAKE_CASE : List[str] = untie_r _SCREAMING_SNAKE_CASE : str = init _SCREAMING_SNAKE_CASE : Optional[Any] = init_range _SCREAMING_SNAKE_CASE : Any = proj_init_std _SCREAMING_SNAKE_CASE : Dict = init_std _SCREAMING_SNAKE_CASE : Any = layer_norm_epsilon super().__init__(eos_token_id=__lowerCamelCase , **__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> List[str]: # Message copied from Transformer-XL documentation logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def UpperCamelCase_ ( self , __lowerCamelCase ) -> int: # Message copied from Transformer-XL documentation raise NotImplementedError( F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
325
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCamelCase__ (__lowerCamelCase ): return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = parser.add_parser("download" ) download_parser.add_argument( "--cache-dir" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to location to store the models" ) download_parser.add_argument( "--force" , action="store_true" , help="Force the model to be download even if already in cache-dir" ) download_parser.add_argument( "--trust-remote-code" , action="store_true" , help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine" , ) download_parser.add_argument("model" , type=__lowerCamelCase , help="Name of the model to download" ) download_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Any = model _SCREAMING_SNAKE_CASE : Optional[int] = cache _SCREAMING_SNAKE_CASE : str = force _SCREAMING_SNAKE_CASE : str = trust_remote_code def UpperCamelCase_ ( self ) -> Optional[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
325
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'layoutlmv3' def __init__( self , __lowerCamelCase=5_0_2_6_5 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-5 , __lowerCamelCase=1 , __lowerCamelCase=0 , __lowerCamelCase=2 , __lowerCamelCase=1_0_2_4 , __lowerCamelCase=1_2_8 , __lowerCamelCase=1_2_8 , __lowerCamelCase=True , __lowerCamelCase=3_2 , __lowerCamelCase=1_2_8 , __lowerCamelCase=6_4 , __lowerCamelCase=2_5_6 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=2_2_4 , __lowerCamelCase=3 , __lowerCamelCase=1_6 , __lowerCamelCase=None , **__lowerCamelCase , ) -> List[Any]: super().__init__( vocab_size=__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 , max_position_embeddings=__lowerCamelCase , type_vocab_size=__lowerCamelCase , initializer_range=__lowerCamelCase , layer_norm_eps=__lowerCamelCase , pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Any = max_ad_position_embeddings _SCREAMING_SNAKE_CASE : List[str] = coordinate_size _SCREAMING_SNAKE_CASE : Optional[Any] = shape_size _SCREAMING_SNAKE_CASE : List[Any] = has_relative_attention_bias _SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins _SCREAMING_SNAKE_CASE : Optional[int] = max_rel_pos _SCREAMING_SNAKE_CASE : Tuple = has_spatial_attention_bias _SCREAMING_SNAKE_CASE : Optional[Any] = rel_ad_pos_bins _SCREAMING_SNAKE_CASE : List[str] = max_rel_ad_pos _SCREAMING_SNAKE_CASE : List[str] = text_embed _SCREAMING_SNAKE_CASE : List[Any] = visual_embed _SCREAMING_SNAKE_CASE : Tuple = input_size _SCREAMING_SNAKE_CASE : List[Any] = num_channels _SCREAMING_SNAKE_CASE : Any = patch_size _SCREAMING_SNAKE_CASE : Union[str, Any] = classifier_dropout class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = version.parse('1.12' ) @property def UpperCamelCase_ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) else: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels"}), ] ) @property def UpperCamelCase_ ( self ) -> float: return 1E-5 @property def UpperCamelCase_ ( self ) -> int: return 1_2 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = -1 , __lowerCamelCase = -1 , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = 3 , __lowerCamelCase = 4_0 , __lowerCamelCase = 4_0 , ) -> Mapping[str, Any]: setattr(processor.image_processor , "apply_ocr" , __lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX _SCREAMING_SNAKE_CASE : Dict = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX _SCREAMING_SNAKE_CASE : List[str] = processor.tokenizer.num_special_tokens_to_add(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = compute_effective_axis_dimension( __lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence _SCREAMING_SNAKE_CASE : Dict = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes _SCREAMING_SNAKE_CASE : List[str] = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) _SCREAMING_SNAKE_CASE : List[str] = self._generate_dummy_images(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = dict( processor( __lowerCamelCase , text=__lowerCamelCase , boxes=__lowerCamelCase , return_tensors=__lowerCamelCase , ) ) return inputs
325
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCAmelCase__: '''simple docstring''' __snake_case = BlenderbotSmallConfig __snake_case = {} __snake_case = 'gelu' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=2_0 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=0 , ) -> List[str]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Tuple = batch_size _SCREAMING_SNAKE_CASE : Dict = seq_length _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : int = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings _SCREAMING_SNAKE_CASE : Optional[int] = eos_token_id _SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id _SCREAMING_SNAKE_CASE : List[str] = bos_token_id def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _SCREAMING_SNAKE_CASE : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : str = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_small_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = TFBlenderbotSmallModel(config=__lowerCamelCase ).get_decoder() _SCREAMING_SNAKE_CASE : Dict = inputs_dict["input_ids"] _SCREAMING_SNAKE_CASE : List[Any] = input_ids[:1, :] _SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict["attention_mask"][:1, :] _SCREAMING_SNAKE_CASE : List[str] = inputs_dict["head_mask"] _SCREAMING_SNAKE_CASE : int = 1 # first forward pass _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _SCREAMING_SNAKE_CASE : Tuple = tf.concat([input_ids, next_tokens] , axis=-1 ) _SCREAMING_SNAKE_CASE : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _SCREAMING_SNAKE_CASE : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] _SCREAMING_SNAKE_CASE : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1E-3 ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, ): if attention_mask is None: _SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast(tf.math.not_equal(__lowerCamelCase, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ), ], axis=-1, ) if head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __snake_case = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __snake_case = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFBlenderbotSmallModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) @require_tokenizers @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' __snake_case = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __snake_case = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase_ ( self ) -> List[Any]: # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(self.src_text , return_tensors="tf" ) _SCREAMING_SNAKE_CASE : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCamelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
325
1
import math def lowerCamelCase__ (__lowerCamelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(__lowerCamelCase ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCamelCase__ (__lowerCamelCase = 10001 ): try: _SCREAMING_SNAKE_CASE : Optional[int] = int(__lowerCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int." ) from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one." ) _SCREAMING_SNAKE_CASE : list[int] = [] _SCREAMING_SNAKE_CASE : str = 2 while len(__lowerCamelCase ) < nth: if is_prime(__lowerCamelCase ): primes.append(__lowerCamelCase ) num += 1 else: num += 1 return primes[len(__lowerCamelCase ) - 1] if __name__ == "__main__": print(f"{solution() = }")
325
from math import isqrt, loga def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 800800, __lowerCamelCase = 800800 ): _SCREAMING_SNAKE_CASE : Optional[int] = degree * loga(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = calculate_prime_numbers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
325
1
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand UpperCamelCase__ =( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) UpperCamelCase__ =( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) UpperCamelCase__ =( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) UpperCamelCase__ =( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) UpperCamelCase__ =( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) UpperCamelCase__ =( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) UpperCamelCase__ =( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = randrange(len(__lowerCamelCase ) ), randrange(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : List[str] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase__ (__lowerCamelCase = 100 ): return (generate_random_hand() for _ in range(__lowerCamelCase )) @pytest.mark.parametrize("hand, expected", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase )._is_flush() == expected @pytest.mark.parametrize("hand, expected", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = PokerHand(__lowerCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase )._hand_type == expected @pytest.mark.parametrize("hand, other, expected", __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase ).compare_with(PokerHand(__lowerCamelCase ) ) == expected @pytest.mark.parametrize("hand, other, expected", generate_random_hands() ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): assert PokerHand(__lowerCamelCase ).compare_with(PokerHand(__lowerCamelCase ) ) == expected def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Any = [PokerHand(__lowerCamelCase ) for hand in SORTED_HANDS] _SCREAMING_SNAKE_CASE : Tuple = poker_hands.copy() shuffle(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = chain(sorted(__lowerCamelCase ) ) for index, hand in enumerate(__lowerCamelCase ): assert hand == poker_hands[index] def lowerCamelCase__ (): # Test that five high straights are compared correctly. _SCREAMING_SNAKE_CASE : Any = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=__lowerCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase__ (): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. _SCREAMING_SNAKE_CASE : Any = PokerHand("2C 4S AS 3D 5C" ) _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : List[Any] = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase__ (): # Problem number 54 from Project Euler # Testing from poker_hands.txt file _SCREAMING_SNAKE_CASE : Dict = 0 _SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.dirname(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : int = os.path.join(__lowerCamelCase, "poker_hands.txt" ) with open(__lowerCamelCase ) as file_hand: for line in file_hand: _SCREAMING_SNAKE_CASE : Any = line[:14].strip() _SCREAMING_SNAKE_CASE : Optional[Any] = line[15:].strip() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = PokerHand(__lowerCamelCase ), PokerHand(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = player.compare_with(__lowerCamelCase ) if output == "Win": answer += 1 assert answer == 376
325
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(__lowerCamelCase ) // (factorial(__lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( 'If a class of 40 students must be arranged into groups of', f"4 for group projects, there are {combinations(40, 4)} ways", 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f"are {combinations(10, 3)} ways that first, second and", 'third place can be awarded.', )
325
1
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class lowerCAmelCase__: '''simple docstring''' __snake_case = 42 __snake_case = None __snake_case = None def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Optional[Any] = Node(1 ) _SCREAMING_SNAKE_CASE : List[Any] = Node(2 ) _SCREAMING_SNAKE_CASE : str = Node(3 ) _SCREAMING_SNAKE_CASE : List[str] = Node(4 ) _SCREAMING_SNAKE_CASE : Optional[Any] = Node(5 ) return tree def lowerCamelCase__ (__lowerCamelCase ): return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def lowerCamelCase__ (__lowerCamelCase ): return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def lowerCamelCase__ (__lowerCamelCase ): return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def lowerCamelCase__ (__lowerCamelCase ): return (max(height(root.left ), height(root.right ) ) + 1) if root else 0 def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : list[Any] = [] if root is None: return output _SCREAMING_SNAKE_CASE : Any = deque([root] ) while process_queue: _SCREAMING_SNAKE_CASE : Optional[Any] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : list[Any] = [] def populate_output(__lowerCamelCase, __lowerCamelCase ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left, level - 1 ) populate_output(root.right, level - 1 ) populate_output(__lowerCamelCase, __lowerCamelCase ) return output def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : list[Any] = [] def populate_output(__lowerCamelCase, __lowerCamelCase ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right, level - 1 ) populate_output(root.left, level - 1 ) populate_output(__lowerCamelCase, __lowerCamelCase ) return output def lowerCamelCase__ (__lowerCamelCase ): if root is None: return [] _SCREAMING_SNAKE_CASE : list[Sequence[Node | None]] = [] _SCREAMING_SNAKE_CASE : List[str] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = height(__lowerCamelCase ) for h in range(1, height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(__lowerCamelCase, __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 else: output.append(get_nodes_from_right_to_left(__lowerCamelCase, __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : int = 0 return output def lowerCamelCase__ (): # Main function for testing. _SCREAMING_SNAKE_CASE : int = make_tree() print(f"""In-order Traversal: {inorder(__lowerCamelCase )}""" ) print(f"""Pre-order Traversal: {preorder(__lowerCamelCase )}""" ) print(f"""Post-order Traversal: {postorder(__lowerCamelCase )}""", "\n" ) print(f"""Height of Tree: {height(__lowerCamelCase )}""", "\n" ) print("Complete Level Order Traversal: " ) print(level_order(__lowerCamelCase ), "\n" ) print("Level-wise order Traversal: " ) for level in range(1, height(__lowerCamelCase ) + 1 ): print(f"""Level {level}:""", get_nodes_from_left_to_right(__lowerCamelCase, level=__lowerCamelCase ) ) print("\nZigZag order Traversal: " ) print(zigzag(__lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 1_2_8 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 2000.0 , __lowerCamelCase = 7_6_8 , __lowerCamelCase = 1_2 , __lowerCamelCase = 1_2 , __lowerCamelCase = 6_4 , __lowerCamelCase = 2_0_4_8 , __lowerCamelCase = 0.1 , ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential( nn.Linear(__lowerCamelCase , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : str = nn.Embedding(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() for lyr_num in range(__lowerCamelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Optional[int] = DecoderLayer(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) self.decoders.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(__lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : Optional[int] = torch.broadcast_to( torch.arange(__lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.position_encoding(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.continuous_inputs_projection(__lowerCamelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Any = self.dropout(__lowerCamelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Any = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : List[str] = [(x, self.encoder_decoder_mask(__lowerCamelCase , __lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : Tuple = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Optional[Any] = lyr( __lowerCamelCase , conditioning_emb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , )[0] _SCREAMING_SNAKE_CASE : int = self.decoder_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.spec_out(__lowerCamelCase ) return spec_out class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.layer[0]( __lowerCamelCase , conditioning_emb=__lowerCamelCase , attention_mask=__lowerCamelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : str = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : Tuple = self.layer[1]( __lowerCamelCase , key_value_states=__lowerCamelCase , attention_mask=__lowerCamelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer[-1](__lowerCamelCase , __lowerCamelCase ) return (hidden_states,) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: # pre_self_attention_layer_norm _SCREAMING_SNAKE_CASE : int = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Any = self.FiLMLayer(__lowerCamelCase , __lowerCamelCase ) # Self-attention block _SCREAMING_SNAKE_CASE : Optional[int] = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.attention( __lowerCamelCase , encoder_hidden_states=__lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.dropout(__lowerCamelCase ) return layer_output class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.film(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.DenseReluDense(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = NewGELUActivation() def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Dict = self.act(self.wi_a(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = self.wi_a(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Optional[int] = self.dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.wo(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.ones(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = eps def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : str = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> torch.Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(__lowerCamelCase , 3.0 )) )) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Any = nn.Linear(__lowerCamelCase , out_features * 2 , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.scale_bias(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = torch.chunk(__lowerCamelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE : Optional[int] = x * (1 + scale) + shift return x
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) _SCREAMING_SNAKE_CASE : List[Any] = str(bin(__lowerCamelCase ) )[2:] # remove the leading "0b" _SCREAMING_SNAKE_CASE : List[str] = str(bin(__lowerCamelCase ) )[2:] # remove the leading "0b" _SCREAMING_SNAKE_CASE : List[Any] = max(len(__lowerCamelCase ), len(__lowerCamelCase ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCamelCase ), b_binary.zfill(__lowerCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
325
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
UpperCamelCase__ ='\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' UpperCamelCase__ =[{'type': 'code', 'content': INSTALL_CONTENT}] UpperCamelCase__ ={ '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
UpperCamelCase__ ={ 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = set() # keep track of all the paths to be checked _SCREAMING_SNAKE_CASE : Union[str, Any] = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _SCREAMING_SNAKE_CASE : List[Any] = queue.pop(0 ) # get the last node from the path _SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: _SCREAMING_SNAKE_CASE : Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _SCREAMING_SNAKE_CASE : Optional[int] = list(__lowerCamelCase ) new_path.append(__lowerCamelCase ) queue.append(__lowerCamelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(__lowerCamelCase ) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _SCREAMING_SNAKE_CASE : Any = [start] _SCREAMING_SNAKE_CASE : Dict = set(__lowerCamelCase ) # Keep tab on distances from `start` node. _SCREAMING_SNAKE_CASE : Tuple = {start: 0, target: -1} while queue: _SCREAMING_SNAKE_CASE : List[Any] = queue.pop(0 ) if node == target: _SCREAMING_SNAKE_CASE : Dict = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(__lowerCamelCase ) queue.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
325
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'timesformer' def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> List[str]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = qkv_bias _SCREAMING_SNAKE_CASE : Tuple = attention_type _SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate
325
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'sentencepiece.bpe.model'} UpperCamelCase__ ={ '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' ), }, } UpperCamelCase__ ={ 'moussaKam/mbarthez': 1024, 'moussaKam/barthez': 1024, 'moussaKam/barthez-orangesum-title': 1024, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['input_ids', 'attention_mask'] def __init__( self , __lowerCamelCase , __lowerCamelCase="<s>" , __lowerCamelCase="</s>" , __lowerCamelCase="</s>" , __lowerCamelCase="<s>" , __lowerCamelCase="<unk>" , __lowerCamelCase="<pad>" , __lowerCamelCase="<mask>" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it _SCREAMING_SNAKE_CASE : Tuple = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_file _SCREAMING_SNAKE_CASE : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Tuple = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} _SCREAMING_SNAKE_CASE : Optional[Any] = len(self.sp_model ) - 1 _SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Union[str, Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _SCREAMING_SNAKE_CASE : Dict = self.sp_model.PieceToId(__lowerCamelCase ) return spm_id if spm_id else self.unk_token_id def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Tuple = "" _SCREAMING_SNAKE_CASE : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def __getstate__( self ) -> int: _SCREAMING_SNAKE_CASE : List[Any] = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Union[str, Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : List[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Dict = {} _SCREAMING_SNAKE_CASE : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : Tuple = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="[CLS]" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<unk>" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<pad>" , __lowerCamelCase="[CLS]" , __lowerCamelCase="[MASK]" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _SCREAMING_SNAKE_CASE : List[Any] = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : str = keep_accents _SCREAMING_SNAKE_CASE : Optional[int] = vocab_file _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: if self.remove_space: _SCREAMING_SNAKE_CASE : List[str] = " ".join(inputs.strip().split() ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = inputs _SCREAMING_SNAKE_CASE : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: _SCREAMING_SNAKE_CASE : str = unicodedata.normalize("NFKD" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: _SCREAMING_SNAKE_CASE : Dict = outputs.lower() return outputs def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): _SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[1:] else: _SCREAMING_SNAKE_CASE : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[str] = "" _SCREAMING_SNAKE_CASE : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : List[Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
1
import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArguments, set_seed, ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument("--model_ckpt", type=__lowerCamelCase, default="microsoft/unixcoder-base-nine" ) parser.add_argument("--num_epochs", type=__lowerCamelCase, default=5 ) parser.add_argument("--batch_size", type=__lowerCamelCase, default=6 ) parser.add_argument("--gradient_accumulation_steps", type=__lowerCamelCase, default=1 ) parser.add_argument("--freeze", type=__lowerCamelCase, default=__lowerCamelCase ) parser.add_argument("--learning_rate", type=__lowerCamelCase, default=5e-4 ) parser.add_argument("--seed", type=__lowerCamelCase, default=0 ) parser.add_argument("--lr_scheduler_type", type=__lowerCamelCase, default="cosine" ) parser.add_argument("--num_warmup_steps", type=__lowerCamelCase, default=10 ) parser.add_argument("--weight_decay", type=__lowerCamelCase, default=0.01 ) parser.add_argument("--output_dir", type=__lowerCamelCase, default="./results" ) return parser.parse_args() UpperCamelCase__ =load('accuracy') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = eval_pred _SCREAMING_SNAKE_CASE : Union[str, Any] = np.argmax(__lowerCamelCase, axis=1 ) return metric.compute(predictions=__lowerCamelCase, references=__lowerCamelCase ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase ) -> None: super().__init__() _SCREAMING_SNAKE_CASE : List[Any] = trainer def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) -> int: if control.should_evaluate: _SCREAMING_SNAKE_CASE : Tuple = deepcopy(__lowerCamelCase ) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix="train" ) return control_copy def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Dict = get_args() set_seed(args.seed ) _SCREAMING_SNAKE_CASE : List[str] = load_dataset("codeparrot/codecomplex", split="train" ) _SCREAMING_SNAKE_CASE : Optional[int] = dataset.train_test_split(test_size=0.2 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = train_test["test"].train_test_split(test_size=0.5 ) _SCREAMING_SNAKE_CASE : Optional[Any] = DatasetDict( { "train": train_test["train"], "test": test_validation["train"], "valid": test_validation["test"], } ) print("Loading tokenizer and model" ) _SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained(args.model_ckpt ) _SCREAMING_SNAKE_CASE : Tuple = tokenizer.eos_token _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt, num_labels=7 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Optional[Any] = ClassLabel(num_classes=7, names=list(set(train_test_validation["train"]["complexity"] ) ) ) def tokenize(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = tokenizer(example["src"], truncation=__lowerCamelCase, max_length=1024 ) _SCREAMING_SNAKE_CASE : List[Any] = labels.straint(example["complexity"] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } _SCREAMING_SNAKE_CASE : Optional[int] = train_test_validation.map( __lowerCamelCase, batched=__lowerCamelCase, remove_columns=train_test_validation["train"].column_names, ) _SCREAMING_SNAKE_CASE : Any = DataCollatorWithPadding(tokenizer=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = TrainingArguments( output_dir=args.output_dir, learning_rate=args.learning_rate, lr_scheduler_type=args.lr_scheduler_type, evaluation_strategy="epoch", save_strategy="epoch", logging_strategy="epoch", per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size, num_train_epochs=args.num_epochs, gradient_accumulation_steps=args.gradient_accumulation_steps, weight_decay=0.01, metric_for_best_model="accuracy", run_name="complexity-java", report_to="wandb", ) _SCREAMING_SNAKE_CASE : List[Any] = Trainer( model=__lowerCamelCase, args=__lowerCamelCase, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["valid"], tokenizer=__lowerCamelCase, data_collator=__lowerCamelCase, compute_metrics=__lowerCamelCase, ) print("Training..." ) trainer.add_callback(CustomCallback(__lowerCamelCase ) ) trainer.train() if __name__ == "__main__": main()
325
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
1
import math def lowerCamelCase__ (__lowerCamelCase ): assert isinstance(__lowerCamelCase, __lowerCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False _SCREAMING_SNAKE_CASE : str = range(3, int(math.sqrt(__lowerCamelCase ) + 1 ), 2 ) return not any(not number % i for i in odd_numbers ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=1, **__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = factor * value _SCREAMING_SNAKE_CASE : List[Any] = value while not is_prime(__lowerCamelCase ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1, **__lowerCamelCase ) return value
325
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): assert x is not None assert y is not None _SCREAMING_SNAKE_CASE : Tuple = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) # declaring the array for storing the dp values _SCREAMING_SNAKE_CASE : List[str] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1, m + 1 ): for j in range(1, n + 1 ): _SCREAMING_SNAKE_CASE : int = 1 if x[i - 1] == y[j - 1] else 0 _SCREAMING_SNAKE_CASE : Union[str, Any] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match ) _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = m, n while i > 0 and j > 0: _SCREAMING_SNAKE_CASE : Optional[int] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: _SCREAMING_SNAKE_CASE : List[str] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": UpperCamelCase__ ='AGGTAB' UpperCamelCase__ ='GXTXAYB' UpperCamelCase__ =4 UpperCamelCase__ ='GTAB' UpperCamelCase__ , UpperCamelCase__ =longest_common_subsequence(a, b) print('len =', ln, ', sub-sequence =', subseq) import doctest doctest.testmod()
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase__ ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
1
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = tempfile.mkdtemp() _SCREAMING_SNAKE_CASE : List[str] = 5 # Realm tok _SCREAMING_SNAKE_CASE : int = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _SCREAMING_SNAKE_CASE : int = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(__lowerCamelCase , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def UpperCamelCase_ ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__lowerCamelCase , ) return block_records def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = self.get_config() _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_retriever() _SCREAMING_SNAKE_CASE : List[Any] = retriever.tokenizer _SCREAMING_SNAKE_CASE : Tuple = np.array([0, 3] , dtype="long" ) _SCREAMING_SNAKE_CASE : str = tokenizer(["Test question"] ).input_ids _SCREAMING_SNAKE_CASE : str = tokenizer( ["the fourth"] , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ).input_ids _SCREAMING_SNAKE_CASE : Any = config.reader_seq_len _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = retriever( __lowerCamelCase , __lowerCamelCase , answer_ids=__lowerCamelCase , max_length=__lowerCamelCase , return_tensors="np" ) self.assertEqual(len(__lowerCamelCase ) , 2 ) self.assertEqual(len(__lowerCamelCase ) , 2 ) self.assertEqual(len(__lowerCamelCase ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 1_0) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 1_0) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Tuple = self.get_config() _SCREAMING_SNAKE_CASE : Dict = self.get_dummy_retriever() _SCREAMING_SNAKE_CASE : str = retriever.tokenizer _SCREAMING_SNAKE_CASE : Any = np.array([0, 3, 5] , dtype="long" ) _SCREAMING_SNAKE_CASE : Any = tokenizer(["Test question"] ).input_ids _SCREAMING_SNAKE_CASE : List[str] = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ).input_ids _SCREAMING_SNAKE_CASE : Union[str, Any] = config.reader_seq_len _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = retriever( __lowerCamelCase , __lowerCamelCase , answer_ids=__lowerCamelCase , max_length=__lowerCamelCase , return_tensors="np" ) self.assertEqual([False, True, True] , __lowerCamelCase ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __lowerCamelCase ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _SCREAMING_SNAKE_CASE : List[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _SCREAMING_SNAKE_CASE : Tuple = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
325
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = 1_3 _SCREAMING_SNAKE_CASE : List[str] = 7 _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : int = 9_9 _SCREAMING_SNAKE_CASE : str = 3_8_4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = 3_7 _SCREAMING_SNAKE_CASE : Union[str, Any] = "gelu" _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 _SCREAMING_SNAKE_CASE : Tuple = 1_6 _SCREAMING_SNAKE_CASE : Dict = 2 _SCREAMING_SNAKE_CASE : Any = 0.02 _SCREAMING_SNAKE_CASE : Any = 3 _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 1_2_8 _SCREAMING_SNAKE_CASE : Optional[int] = 2 _SCREAMING_SNAKE_CASE : int = 9 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = TFConvBertForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : str = TFConvBertForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_choices _SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = self.num_labels _SCREAMING_SNAKE_CASE : Tuple = TFConvBertForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : int = TFConvBertModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True if hasattr(__lowerCamelCase , "use_cache" ): _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = os.path.join(__lowerCamelCase , "saved_model" , "1" ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.models.load_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : List[Any] = outputs["encoder_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs["encoder_attentions"] else: _SCREAMING_SNAKE_CASE : List[str] = outputs["hidden_states"] _SCREAMING_SNAKE_CASE : Dict = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) _SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = [1, 6, 7_6_8] self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
325
1
import doctest from collections import deque import numpy as np class lowerCAmelCase__: '''simple docstring''' def __init__( self ) -> None: _SCREAMING_SNAKE_CASE : str = [2, 1, 2, -1] _SCREAMING_SNAKE_CASE : Tuple = [1, 2, 3, 4] def UpperCamelCase_ ( self ) -> list[float]: _SCREAMING_SNAKE_CASE : Dict = len(self.first_signal ) _SCREAMING_SNAKE_CASE : Optional[int] = len(self.second_signal ) _SCREAMING_SNAKE_CASE : Tuple = max(__lowerCamelCase , __lowerCamelCase ) # create a zero matrix of max_length x max_length _SCREAMING_SNAKE_CASE : Tuple = [[0] * max_length for i in range(__lowerCamelCase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : int = deque(self.second_signal ) rotated_signal.rotate(__lowerCamelCase ) for j, item in enumerate(__lowerCamelCase ): matrix[i][j] += item # multiply the matrix with the first signal _SCREAMING_SNAKE_CASE : int = np.matmul(np.transpose(__lowerCamelCase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(__lowerCamelCase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
325
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
1
import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ComputeEnvironment.AMAZON_SAGEMAKER __snake_case = True __snake_case = 'ml.p3.2xlarge' __snake_case = 'accelerate_sagemaker_execution_role' __snake_case = 'hf-sm' __snake_case = 'us-east-1' __snake_case = 1 __snake_case = 'accelerate-sagemaker-1' __snake_case = '1.6' __snake_case = '4.4' __snake_case = 'train.py' __snake_case = [ '--model_name_or_path', 'bert', '--do_train', 'False', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] __snake_case = [ '--model_name_or_path', 'bert', '--do_train', '--do_test', 'False', '--do_predict', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. _SCREAMING_SNAKE_CASE : Dict = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args["model_name_or_path"] , __lowerCamelCase ) assert isinstance(converted_args["do_train"] , __lowerCamelCase ) assert isinstance(converted_args["epochs"] , __lowerCamelCase ) assert isinstance(converted_args["learning_rate"] , __lowerCamelCase ) assert isinstance(converted_args["max_steps"] , __lowerCamelCase ) with pytest.raises(__lowerCamelCase ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
325
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2] _SCREAMING_SNAKE_CASE : List[str] = True if "large" in model_name or "huge" in model_name else False _SCREAMING_SNAKE_CASE : Tuple = True if "large" in model_name or "huge" in model_name else False _SCREAMING_SNAKE_CASE : Union[str, Any] = True if "large" in model_name or "huge" in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: _SCREAMING_SNAKE_CASE : Any = [3, 3, 3, 3] _SCREAMING_SNAKE_CASE : int = [5, 5, 5, 5] elif "fl4" in model_name: _SCREAMING_SNAKE_CASE : Optional[int] = [4, 4, 4, 4] _SCREAMING_SNAKE_CASE : Optional[Any] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: _SCREAMING_SNAKE_CASE : Tuple = [3, 3, 3, 3] if "lrf" in model_name: _SCREAMING_SNAKE_CASE : Optional[Any] = [3, 3, 3, 3] else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [2, 2, 2, 2] if "tiny" in model_name: _SCREAMING_SNAKE_CASE : Dict = 96 elif "small" in model_name: _SCREAMING_SNAKE_CASE : Tuple = 96 elif "base" in model_name: _SCREAMING_SNAKE_CASE : Optional[int] = 128 elif "large" in model_name: _SCREAMING_SNAKE_CASE : str = 192 elif "xlarge" in model_name: _SCREAMING_SNAKE_CASE : Dict = 256 elif "huge" in model_name: _SCREAMING_SNAKE_CASE : List[Any] = 352 # set label information _SCREAMING_SNAKE_CASE : Optional[Any] = "huggingface/label-files" if "large" in model_name or "huge" in model_name: _SCREAMING_SNAKE_CASE : Optional[int] = "imagenet-22k-id2label.json" else: _SCREAMING_SNAKE_CASE : List[Any] = "imagenet-1k-id2label.json" _SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(__lowerCamelCase, __lowerCamelCase, repo_type="dataset" ), "r" ) ) _SCREAMING_SNAKE_CASE : Optional[int] = {int(__lowerCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : Optional[int] = FocalNetConfig( embed_dim=__lowerCamelCase, depths=__lowerCamelCase, focal_levels=__lowerCamelCase, focal_windows=__lowerCamelCase, use_conv_embed=__lowerCamelCase, idalabel=__lowerCamelCase, labelaid=__lowerCamelCase, use_post_layernorm=__lowerCamelCase, use_layerscale=__lowerCamelCase, ) return config def lowerCamelCase__ (__lowerCamelCase ): if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("patch_embed.norm", "embeddings.norm" ) if "layers" in name: _SCREAMING_SNAKE_CASE : List[Any] = "encoder." + name if "encoder.layers" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("encoder.layers", "encoder.stages" ) if "downsample.proj" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("downsample.proj", "downsample.projection" ) if "blocks" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("blocks", "layers" ) if "modulation.f.weight" in name or "modulation.f.bias" in name: _SCREAMING_SNAKE_CASE : Any = name.replace("modulation.f", "modulation.projection_in" ) if "modulation.h.weight" in name or "modulation.h.bias" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("modulation.h", "modulation.projection_context" ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("modulation.proj", "modulation.projection_out" ) if name == "norm.weight": _SCREAMING_SNAKE_CASE : Any = "layernorm.weight" if name == "norm.bias": _SCREAMING_SNAKE_CASE : List[str] = "layernorm.bias" if "head" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("head", "classifier" ) else: _SCREAMING_SNAKE_CASE : Dict = "focalnet." + name return name def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase=False ): # fmt: off _SCREAMING_SNAKE_CASE : Any = { "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth", "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth", "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth", "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth", "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth", "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth", "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth", "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth", "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth", "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth", } # fmt: on _SCREAMING_SNAKE_CASE : Any = model_name_to_url[model_name] print("Checkpoint URL: ", __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = torch.hub.load_state_dict_from_url(__lowerCamelCase, map_location="cpu" )["model"] # rename keys for key in state_dict.copy().keys(): _SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = val _SCREAMING_SNAKE_CASE : int = get_focalnet_config(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = FocalNetForImageClassification(__lowerCamelCase ) model.eval() # load state dict model.load_state_dict(__lowerCamelCase ) # verify conversion _SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" _SCREAMING_SNAKE_CASE : Optional[int] = BitImageProcessor( do_resize=__lowerCamelCase, size={"shortest_edge": 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__lowerCamelCase, crop_size=224, do_normalize=__lowerCamelCase, image_mean=__lowerCamelCase, image_std=__lowerCamelCase, ) _SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(__lowerCamelCase, stream=__lowerCamelCase ).raw ) _SCREAMING_SNAKE_CASE : Dict = processor(images=__lowerCamelCase, return_tensors="pt" ) _SCREAMING_SNAKE_CASE : Any = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ) _SCREAMING_SNAKE_CASE : Dict = image_transforms(__lowerCamelCase ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __lowerCamelCase, atol=1e-4 ) _SCREAMING_SNAKE_CASE : List[Any] = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = outputs.logits.argmax(-1 ).item() print("Predicted class:", model.config.idalabel[predicted_class_idx] ) print("First values of logits:", outputs.logits[0, :3] ) if model_name == "focalnet-tiny": _SCREAMING_SNAKE_CASE : str = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": _SCREAMING_SNAKE_CASE : str = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": _SCREAMING_SNAKE_CASE : List[str] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": _SCREAMING_SNAKE_CASE : int = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3], __lowerCamelCase, atol=1e-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) if push_to_hub: print(f"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(f"""{model_name}""" ) processor.push_to_hub(f"""{model_name}""" ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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 to push the model and processor to the hub.', ) UpperCamelCase__ =parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
325
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ =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). UpperCamelCase__ =[0, 25, 50] UpperCamelCase__ =[25, 50, 75] UpperCamelCase__ =fuzz.membership.trimf(X, abca) UpperCamelCase__ =fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCamelCase__ =np.ones(75) UpperCamelCase__ =np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCamelCase__ =fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCamelCase__ =young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCamelCase__ =young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCamelCase__ =fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCamelCase__ =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()
325
1
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline UpperCamelCase__ ={ 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": UpperCamelCase__ ='hopper-medium-v2' UpperCamelCase__ =gym.make(env_name) UpperCamelCase__ =ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) UpperCamelCase__ =env.reset() UpperCamelCase__ =0 UpperCamelCase__ =0 UpperCamelCase__ =1000 UpperCamelCase__ =[obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy UpperCamelCase__ =pipeline(obs, planning_horizon=32) # execute action in environment UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ =env.step(denorm_actions) UpperCamelCase__ =env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f"Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:" f" {total_score}" ) # save observations for rendering rollout.append(next_observation.copy()) UpperCamelCase__ =next_observation except KeyboardInterrupt: pass print(f"Total reward: {total_reward}")
325
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'roberta' def __init__( self , __lowerCamelCase=5_0_2_6_5 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-12 , __lowerCamelCase=1 , __lowerCamelCase=0 , __lowerCamelCase=2 , __lowerCamelCase="absolute" , __lowerCamelCase=True , __lowerCamelCase=None , **__lowerCamelCase , ) -> List[Any]: super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size _SCREAMING_SNAKE_CASE : List[Any] = hidden_size _SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers _SCREAMING_SNAKE_CASE : Tuple = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act _SCREAMING_SNAKE_CASE : int = intermediate_size _SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Any = max_position_embeddings _SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size _SCREAMING_SNAKE_CASE : Any = initializer_range _SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps _SCREAMING_SNAKE_CASE : Optional[Any] = position_embedding_type _SCREAMING_SNAKE_CASE : str = use_cache _SCREAMING_SNAKE_CASE : Optional[Any] = classifier_dropout class lowerCAmelCase__( __lowercase ): '''simple docstring''' @property def UpperCamelCase_ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE : str = {0: "batch", 1: "choice", 2: "sequence"} else: _SCREAMING_SNAKE_CASE : Optional[Any] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
325
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lowerCamelCase, max_perimeter + 1 ): _SCREAMING_SNAKE_CASE : List[Any] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase__ (__lowerCamelCase = 1000 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = pythagorean_triple(__lowerCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
325
1
from __future__ import annotations def lowerCamelCase__ (__lowerCamelCase ): if not nums: return 0 _SCREAMING_SNAKE_CASE : str = nums[0] _SCREAMING_SNAKE_CASE : str = 0 for num in nums[1:]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = ( max_excluding + num, max(__lowerCamelCase, __lowerCamelCase ), ) return max(__lowerCamelCase, __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
325
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # ===== initialization ===== _SCREAMING_SNAKE_CASE : List[Any] = Mock() _SCREAMING_SNAKE_CASE : Optional[Any] = conn, Mock() _SCREAMING_SNAKE_CASE : Dict = iter([1, None] ) _SCREAMING_SNAKE_CASE : Optional[Any] = lambda __lowerCamelCase : next(__lowerCamelCase ) # ===== invoke ===== send_file(filename="mytext.txt", testing=__lowerCamelCase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
325
1
from __future__ import annotations from random import choice def lowerCamelCase__ (__lowerCamelCase ): return choice(__lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = random_pivot(__lowerCamelCase ) # partition based on pivot # linear time _SCREAMING_SNAKE_CASE : Dict = [e for e in lst if e < pivot] _SCREAMING_SNAKE_CASE : str = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__lowerCamelCase ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__lowerCamelCase ) < k - 1: return kth_number(__lowerCamelCase, k - len(__lowerCamelCase ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__lowerCamelCase, __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
325
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['image_processor', 'tokenizer'] __snake_case = 'BlipImageProcessor' __snake_case = 'AutoTokenizer' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE : List[str] = qformer_tokenizer def __call__( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE : Any = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) encoding.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.qformer_tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : str = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE : List[Any] = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) encoding.update(__lowerCamelCase ) return encoding def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Union[str, Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> str: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> Any: if os.path.isfile(__lowerCamelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(__lowerCamelCase ) return super().save_pretrained(__lowerCamelCase , **__lowerCamelCase ) @classmethod def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(__lowerCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_arguments_from_pretrained(__lowerCamelCase , **__lowerCamelCase ) args.append(__lowerCamelCase ) return cls(*__lowerCamelCase )
325
1
import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = DebertaTokenizer __snake_case = True __snake_case = DebertaTokenizerFast def UpperCamelCase_ ( self ) -> List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _SCREAMING_SNAKE_CASE : Optional[Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "[UNK]", ] _SCREAMING_SNAKE_CASE : str = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) _SCREAMING_SNAKE_CASE : List[str] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] _SCREAMING_SNAKE_CASE : Dict = {"unk_token": "[UNK]"} _SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__lowerCamelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__lowerCamelCase ) ) def UpperCamelCase_ ( self , **__lowerCamelCase ) -> Dict: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = "lower newer" _SCREAMING_SNAKE_CASE : List[str] = "lower newer" return input_text, output_text def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() _SCREAMING_SNAKE_CASE : Union[str, Any] = "lower newer" _SCREAMING_SNAKE_CASE : Optional[int] = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"] _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = tokens + [tokenizer.unk_token] _SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() _SCREAMING_SNAKE_CASE : List[Any] = tokenizer("Hello" , "World" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd["token_type_ids"] , __lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained("microsoft/deberta-base" ) _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode("sequence builders" , add_special_tokens=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode("multi-sequence build" , add_special_tokens=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = tokenizer.encode( "sequence builders" , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = tokenizer.encode( "sequence builders" , "multi-sequence build" , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase , __lowerCamelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: _SCREAMING_SNAKE_CASE : Any = tokenizer_class.from_pretrained("microsoft/deberta-base" ) _SCREAMING_SNAKE_CASE : Optional[int] = [ "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations", "ALBERT incorporates two parameter reduction techniques", "The first one is a factorized embedding parameterization. By decomposing the large vocabulary" " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of" " vocabulary embedding.", ] _SCREAMING_SNAKE_CASE : List[Any] = tokenizer(__lowerCamelCase , padding=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = [tokenizer.decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) for seq in encoding["input_ids"]] # fmt: off _SCREAMING_SNAKE_CASE : int = { "input_ids": [ [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 3_5, 8_3, 2_5_1_9_1, 1_6_3, 1_8_8_5_4, 1_3, 1_2_1_5_6, 1_2, 1_6_1_0_1, 2_5_3_7_6, 1_3_8_0_7, 9, 2_2_2_0_5, 2_7_8_9_3, 1_6_3_5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 2_4_5_3_6, 8_0, 4_3_7_9_7, 4_8_7_8, 7_3_7_3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_3_3, 7_8, 6_5, 1_6, 1_0, 3_7_2_4, 1_5_3_8, 3_3_1_8_3, 1_1_3_0_3, 4_3_7_9_7, 1_9_3_8, 4, 8_7_0, 2_4_1_6_5, 2_9_1_0_5, 5, 7_3_9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 3_6_1_7_3, 8_8, 8_0, 6_5_0, 7_8_2_1, 4_5_9_4_0, 6, 5_2, 2_5_5_9, 5, 1_8_3_6, 9, 5, 7_3_9_7, 1_3_1_7_1, 3_1, 5, 1_8_3_6, 9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 4, 2] ], "token_type_ids": [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on _SCREAMING_SNAKE_CASE : Optional[Any] = [ "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations", "ALBERT incorporates two parameter reduction techniques", "The first one is a factorized embedding parameterization. By decomposing the large vocabulary" " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of" " vocabulary embedding.", ] self.assertDictEqual(encoding.data , __lowerCamelCase ) for expected, decoded in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(__lowerCamelCase , __lowerCamelCase )
325
from maths.prime_check import is_prime def lowerCamelCase__ (__lowerCamelCase ): if not isinstance(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(__lowerCamelCase ) if is_prime(__lowerCamelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCamelCase__ (__lowerCamelCase ): return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = parser.add_parser("download" ) download_parser.add_argument( "--cache-dir" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to location to store the models" ) download_parser.add_argument( "--force" , action="store_true" , help="Force the model to be download even if already in cache-dir" ) download_parser.add_argument( "--trust-remote-code" , action="store_true" , help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine" , ) download_parser.add_argument("model" , type=__lowerCamelCase , help="Name of the model to download" ) download_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Any = model _SCREAMING_SNAKE_CASE : Optional[int] = cache _SCREAMING_SNAKE_CASE : str = force _SCREAMING_SNAKE_CASE : str = trust_remote_code def UpperCamelCase_ ( self ) -> Optional[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
325
1
import numpy # List of input, output pairs UpperCamelCase__ =( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCamelCase__ =(((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCamelCase__ =[2, 4, 1, 5] UpperCamelCase__ =len(train_data) UpperCamelCase__ =0.009 def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase="train" ): return calculate_hypothesis_value(__lowerCamelCase, __lowerCamelCase ) - output( __lowerCamelCase, __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for i in range(len(__lowerCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=m ): _SCREAMING_SNAKE_CASE : Any = 0 for i in range(__lowerCamelCase ): if index == -1: summation_value += _error(__lowerCamelCase ) else: summation_value += _error(__lowerCamelCase ) * train_data[i][0][index] return summation_value def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = summation_of_cost_derivative(__lowerCamelCase, __lowerCamelCase ) / m return cost_derivative_value def lowerCamelCase__ (): global parameter_vector # Tune these values to set a tolerance value for predicted output _SCREAMING_SNAKE_CASE : Tuple = 0.00_0002 _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : Any = 0 while True: j += 1 _SCREAMING_SNAKE_CASE : List[str] = [0, 0, 0, 0] for i in range(0, len(__lowerCamelCase ) ): _SCREAMING_SNAKE_CASE : str = get_cost_derivative(i - 1 ) _SCREAMING_SNAKE_CASE : Any = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( __lowerCamelCase, __lowerCamelCase, atol=__lowerCamelCase, rtol=__lowerCamelCase, ): break _SCREAMING_SNAKE_CASE : Tuple = temp_parameter_vector print(("Number of iterations:", j) ) def lowerCamelCase__ (): for i in range(len(__lowerCamelCase ) ): print(("Actual output value:", output(__lowerCamelCase, "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(__lowerCamelCase, "test" )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
325
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCAmelCase__: '''simple docstring''' __snake_case = BlenderbotSmallConfig __snake_case = {} __snake_case = 'gelu' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=2_0 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=0 , ) -> List[str]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Tuple = batch_size _SCREAMING_SNAKE_CASE : Dict = seq_length _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : int = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings _SCREAMING_SNAKE_CASE : Optional[int] = eos_token_id _SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id _SCREAMING_SNAKE_CASE : List[str] = bos_token_id def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _SCREAMING_SNAKE_CASE : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : str = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_small_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = TFBlenderbotSmallModel(config=__lowerCamelCase ).get_decoder() _SCREAMING_SNAKE_CASE : Dict = inputs_dict["input_ids"] _SCREAMING_SNAKE_CASE : List[Any] = input_ids[:1, :] _SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict["attention_mask"][:1, :] _SCREAMING_SNAKE_CASE : List[str] = inputs_dict["head_mask"] _SCREAMING_SNAKE_CASE : int = 1 # first forward pass _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _SCREAMING_SNAKE_CASE : Tuple = tf.concat([input_ids, next_tokens] , axis=-1 ) _SCREAMING_SNAKE_CASE : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _SCREAMING_SNAKE_CASE : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] _SCREAMING_SNAKE_CASE : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1E-3 ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, ): if attention_mask is None: _SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast(tf.math.not_equal(__lowerCamelCase, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ), ], axis=-1, ) if head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __snake_case = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __snake_case = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFBlenderbotSmallModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) @require_tokenizers @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' __snake_case = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __snake_case = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase_ ( self ) -> List[Any]: # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(self.src_text , return_tensors="tf" ) _SCREAMING_SNAKE_CASE : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCamelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
325
1
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['pixel_values'] def __init__( self , __lowerCamelCase = True , __lowerCamelCase = 3_2 , __lowerCamelCase=PILImageResampling.BILINEAR , __lowerCamelCase = True , **__lowerCamelCase , ) -> None: _SCREAMING_SNAKE_CASE : int = do_resize _SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale _SCREAMING_SNAKE_CASE : List[Any] = size_divisor _SCREAMING_SNAKE_CASE : List[str] = resample super().__init__(**__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase ) -> np.ndarray: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = get_image_size(__lowerCamelCase ) # Rounds the height and width down to the closest multiple of size_divisor _SCREAMING_SNAKE_CASE : Optional[Any] = height // size_divisor * size_divisor _SCREAMING_SNAKE_CASE : List[Any] = width // size_divisor * size_divisor _SCREAMING_SNAKE_CASE : Optional[int] = resize(__lowerCamelCase , (new_h, new_w) , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) return image def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase ) -> np.ndarray: return rescale(image=__lowerCamelCase , scale=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = ChannelDimension.FIRST , **__lowerCamelCase , ) -> BatchFeature: _SCREAMING_SNAKE_CASE : List[Any] = do_resize if do_resize is not None else self.do_resize _SCREAMING_SNAKE_CASE : int = do_rescale if do_rescale is not None else self.do_rescale _SCREAMING_SNAKE_CASE : Optional[int] = size_divisor if size_divisor is not None else self.size_divisor _SCREAMING_SNAKE_CASE : Optional[int] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("size_divisor is required for resizing" ) _SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(__lowerCamelCase ) if not valid_images(__lowerCamelCase ): raise ValueError("Invalid image(s)" ) # All transformations expect numpy arrays. _SCREAMING_SNAKE_CASE : str = [to_numpy_array(__lowerCamelCase ) for img in images] if do_resize: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.resize(__lowerCamelCase , size_divisor=__lowerCamelCase , resample=__lowerCamelCase ) for image in images] if do_rescale: _SCREAMING_SNAKE_CASE : Dict = [self.rescale(__lowerCamelCase , scale=1 / 2_5_5 ) for image in images] _SCREAMING_SNAKE_CASE : Any = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images] _SCREAMING_SNAKE_CASE : Any = {"pixel_values": images} return BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase )
325
from math import isqrt, loga def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 800800, __lowerCamelCase = 800800 ): _SCREAMING_SNAKE_CASE : Optional[int] = degree * loga(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = calculate_prime_numbers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
325
1
def lowerCamelCase__ (__lowerCamelCase ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
325
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(__lowerCamelCase ) // (factorial(__lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( 'If a class of 40 students must be arranged into groups of', f"4 for group projects, there are {combinations(40, 4)} ways", 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f"are {combinations(10, 3)} ways that first, second and", 'third place can be awarded.', )
325
1
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch UpperCamelCase__ =random.Random() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=1.0, __lowerCamelCase=None, __lowerCamelCase=None ): if rng is None: _SCREAMING_SNAKE_CASE : List[str] = global_rng _SCREAMING_SNAKE_CASE : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=7 , __lowerCamelCase=4_0_0 , __lowerCamelCase=2_0_0_0 , __lowerCamelCase=1 , __lowerCamelCase=0.0 , __lowerCamelCase=1_6_0_0_0 , __lowerCamelCase=True , __lowerCamelCase=8_0 , __lowerCamelCase=1_6 , __lowerCamelCase=6_4 , __lowerCamelCase="hann_window" , __lowerCamelCase=8_0 , __lowerCamelCase=7_6_0_0 , __lowerCamelCase=1E-10 , __lowerCamelCase=True , ) -> List[str]: _SCREAMING_SNAKE_CASE : Any = parent _SCREAMING_SNAKE_CASE : int = batch_size _SCREAMING_SNAKE_CASE : str = min_seq_length _SCREAMING_SNAKE_CASE : Any = max_seq_length _SCREAMING_SNAKE_CASE : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _SCREAMING_SNAKE_CASE : Dict = feature_size _SCREAMING_SNAKE_CASE : List[Any] = padding_value _SCREAMING_SNAKE_CASE : Union[str, Any] = sampling_rate _SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize _SCREAMING_SNAKE_CASE : Tuple = num_mel_bins _SCREAMING_SNAKE_CASE : List[str] = hop_length _SCREAMING_SNAKE_CASE : Optional[Any] = win_length _SCREAMING_SNAKE_CASE : List[str] = win_function _SCREAMING_SNAKE_CASE : Dict = fmin _SCREAMING_SNAKE_CASE : Tuple = fmax _SCREAMING_SNAKE_CASE : Optional[int] = mel_floor _SCREAMING_SNAKE_CASE : Dict = return_attention_mask def UpperCamelCase_ ( self ) -> Dict: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def UpperCamelCase_ ( self , __lowerCamelCase=False , __lowerCamelCase=False ) -> Union[str, Any]: def _flatten(__lowerCamelCase ): return list(itertools.chain(*__lowerCamelCase ) ) if equal_length: _SCREAMING_SNAKE_CASE : str = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _SCREAMING_SNAKE_CASE : List[str] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _SCREAMING_SNAKE_CASE : str = [np.asarray(__lowerCamelCase ) for x in speech_inputs] return speech_inputs def UpperCamelCase_ ( self , __lowerCamelCase=False , __lowerCamelCase=False ) -> Tuple: if equal_length: _SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _SCREAMING_SNAKE_CASE : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _SCREAMING_SNAKE_CASE : str = [np.asarray(__lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = SpeechTaFeatureExtractor def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Union[str, Any] = SpeechTaFeatureExtractionTester(self ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Union[str, Any]: self.assertTrue(np.all(np.mean(__lowerCamelCase , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__lowerCamelCase , axis=0 ) - 1 ) < 1E-3 ) ) def UpperCamelCase_ ( self ) -> Dict: # Tests that all call wrap to encode_plus and batch_encode_plus _SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _SCREAMING_SNAKE_CASE : Tuple = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(__lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input _SCREAMING_SNAKE_CASE : Any = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values _SCREAMING_SNAKE_CASE : str = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) # Test batched _SCREAMING_SNAKE_CASE : Any = feat_extract(__lowerCamelCase , return_tensors="np" ).input_values _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract(__lowerCamelCase , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCamelCase , __lowerCamelCase ): self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE : Tuple = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : str = ["longest", "max_length", "do_not_pad"] _SCREAMING_SNAKE_CASE : Dict = [None, 1_6_0_0, None] for max_length, padding in zip(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = feat_extract(__lowerCamelCase , padding=__lowerCamelCase , max_length=__lowerCamelCase , return_tensors="np" ) _SCREAMING_SNAKE_CASE : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE : str = range(8_0_0 , 1_4_0_0 , 2_0_0 ) _SCREAMING_SNAKE_CASE : List[str] = [floats_list((1, x) )[0] for x in lengths] _SCREAMING_SNAKE_CASE : int = ["longest", "max_length", "do_not_pad"] _SCREAMING_SNAKE_CASE : int = [None, 1_6_0_0, None] for max_length, padding in zip(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = feat_extract(__lowerCamelCase , max_length=__lowerCamelCase , padding=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE : int = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : int = feat_extract( __lowerCamelCase , truncation=__lowerCamelCase , max_length=1_0_0_0 , padding="max_length" , return_tensors="np" ) _SCREAMING_SNAKE_CASE : Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : Tuple = feat_extract( __lowerCamelCase , truncation=__lowerCamelCase , max_length=1_0_0_0 , padding="longest" , return_tensors="np" ) _SCREAMING_SNAKE_CASE : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) _SCREAMING_SNAKE_CASE : int = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : Any = feat_extract( __lowerCamelCase , truncation=__lowerCamelCase , max_length=2_0_0_0 , padding="longest" , return_tensors="np" ) _SCREAMING_SNAKE_CASE : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE : str = np.random.rand(1_0_0 ).astype(np.floataa ) _SCREAMING_SNAKE_CASE : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _SCREAMING_SNAKE_CASE : Any = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _SCREAMING_SNAKE_CASE : Any = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def UpperCamelCase_ ( self ) -> int: # Tests that all call wrap to encode_plus and batch_encode_plus _SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _SCREAMING_SNAKE_CASE : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _SCREAMING_SNAKE_CASE : Tuple = [np.asarray(__lowerCamelCase ) for speech_input in speech_inputs] # Test feature size _SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(audio_target=__lowerCamelCase , padding=__lowerCamelCase , return_tensors="np" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input _SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_values _SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) # Test batched _SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(__lowerCamelCase , return_tensors="np" ).input_values _SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(__lowerCamelCase , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCamelCase , __lowerCamelCase ): self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. _SCREAMING_SNAKE_CASE : List[str] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _SCREAMING_SNAKE_CASE : List[str] = np.asarray(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = feature_extractor(__lowerCamelCase , return_tensors="np" ).input_values _SCREAMING_SNAKE_CASE : Dict = feature_extractor(__lowerCamelCase , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCamelCase , __lowerCamelCase ): self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.feat_extract_tester.prepare_inputs_for_target() _SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) _SCREAMING_SNAKE_CASE : List[str] = feat_extract.model_input_names[0] _SCREAMING_SNAKE_CASE : Dict = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(__lowerCamelCase ) == len(__lowerCamelCase ) for x, y in zip(__lowerCamelCase , processed_features[input_name] ) ) ) _SCREAMING_SNAKE_CASE : Any = self.feat_extract_tester.prepare_inputs_for_target(equal_length=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = BatchFeature({input_name: speech_inputs} , tensor_type="np" ) _SCREAMING_SNAKE_CASE : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: _SCREAMING_SNAKE_CASE : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Tuple = self.feat_extract_tester.prepare_inputs_for_target(equal_length=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) _SCREAMING_SNAKE_CASE : List[Any] = feat_extract.model_input_names[0] _SCREAMING_SNAKE_CASE : str = BatchFeature({input_name: speech_inputs} , tensor_type="pt" ) _SCREAMING_SNAKE_CASE : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: _SCREAMING_SNAKE_CASE : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.model_input_names[0] _SCREAMING_SNAKE_CASE : Optional[int] = BatchFeature({input_name: speech_inputs} ) _SCREAMING_SNAKE_CASE : int = feat_extract.num_mel_bins # hack! _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.pad(__lowerCamelCase , padding="longest" , return_tensors="np" )[input_name] _SCREAMING_SNAKE_CASE : List[str] = feat_extract.pad(__lowerCamelCase , padding="longest" , return_tensors="pt" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : str = self.feat_extract_dict _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extraction_class(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.feat_extract_tester.prepare_inputs_for_target() _SCREAMING_SNAKE_CASE : List[Any] = [len(__lowerCamelCase ) for x in speech_inputs] _SCREAMING_SNAKE_CASE : Any = feat_extract.model_input_names[0] _SCREAMING_SNAKE_CASE : Dict = BatchFeature({input_name: speech_inputs} ) _SCREAMING_SNAKE_CASE : Dict = feat_extract.num_mel_bins # hack! _SCREAMING_SNAKE_CASE : Any = feat_extract.pad(__lowerCamelCase , padding="longest" , return_tensors="np" ) self.assertIn("attention_mask" , __lowerCamelCase ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Optional[Any] = self.feat_extract_dict _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.feat_extract_tester.prepare_inputs_for_target() _SCREAMING_SNAKE_CASE : Any = [len(__lowerCamelCase ) for x in speech_inputs] _SCREAMING_SNAKE_CASE : str = feat_extract.model_input_names[0] _SCREAMING_SNAKE_CASE : str = BatchFeature({input_name: speech_inputs} ) _SCREAMING_SNAKE_CASE : List[Any] = min(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = feat_extract.num_mel_bins # hack! _SCREAMING_SNAKE_CASE : Tuple = feat_extract.pad( __lowerCamelCase , padding="max_length" , max_length=__lowerCamelCase , truncation=__lowerCamelCase , return_tensors="np" ) self.assertIn("attention_mask" , __lowerCamelCase ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: from datasets import load_dataset _SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech _SCREAMING_SNAKE_CASE : Tuple = ds.sort("id" ).select(range(__lowerCamelCase ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def UpperCamelCase_ ( self ) -> Tuple: # fmt: off _SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [2.3_804E-03, 2.0_752E-03, 1.9_836E-03, 2.1_057E-03, 1.6_174E-03, 3.0_518E-04, 9.1_553E-05, 3.3_569E-04, 9.7_656E-04, 1.8_311E-03, 2.0_142E-03, 2.1_057E-03, 1.7_395E-03, 4.5_776E-04, -3.9_673E-04, 4.5_776E-04, 1.0_071E-03, 9.1_553E-05, 4.8_828E-04, 1.1_597E-03, 7.3_242E-04, 9.4_604E-04, 1.8_005E-03, 1.8_311E-03, 8.8_501E-04, 4.2_725E-04, 4.8_828E-04, 7.3_242E-04, 1.0_986E-03, 2.1_057E-03] ) # fmt: on _SCREAMING_SNAKE_CASE : List[str] = self._load_datasamples(1 ) _SCREAMING_SNAKE_CASE : Optional[Any] = SpeechTaFeatureExtractor() _SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(__lowerCamelCase , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0] , __lowerCamelCase , atol=1E-6 ) ) def UpperCamelCase_ ( self ) -> Optional[int]: # fmt: off _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on _SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = SpeechTaFeatureExtractor() _SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor(audio_target=__lowerCamelCase , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , __lowerCamelCase , atol=1E-4 ) )
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 1_2_8 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 2000.0 , __lowerCamelCase = 7_6_8 , __lowerCamelCase = 1_2 , __lowerCamelCase = 1_2 , __lowerCamelCase = 6_4 , __lowerCamelCase = 2_0_4_8 , __lowerCamelCase = 0.1 , ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential( nn.Linear(__lowerCamelCase , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : str = nn.Embedding(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() for lyr_num in range(__lowerCamelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Optional[int] = DecoderLayer(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) self.decoders.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(__lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : Optional[int] = torch.broadcast_to( torch.arange(__lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.position_encoding(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.continuous_inputs_projection(__lowerCamelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Any = self.dropout(__lowerCamelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Any = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : List[str] = [(x, self.encoder_decoder_mask(__lowerCamelCase , __lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : Tuple = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Optional[Any] = lyr( __lowerCamelCase , conditioning_emb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , )[0] _SCREAMING_SNAKE_CASE : int = self.decoder_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.spec_out(__lowerCamelCase ) return spec_out class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.layer[0]( __lowerCamelCase , conditioning_emb=__lowerCamelCase , attention_mask=__lowerCamelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : str = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : Tuple = self.layer[1]( __lowerCamelCase , key_value_states=__lowerCamelCase , attention_mask=__lowerCamelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer[-1](__lowerCamelCase , __lowerCamelCase ) return (hidden_states,) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: # pre_self_attention_layer_norm _SCREAMING_SNAKE_CASE : int = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Any = self.FiLMLayer(__lowerCamelCase , __lowerCamelCase ) # Self-attention block _SCREAMING_SNAKE_CASE : Optional[int] = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.attention( __lowerCamelCase , encoder_hidden_states=__lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.dropout(__lowerCamelCase ) return layer_output class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.film(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.DenseReluDense(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = NewGELUActivation() def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Dict = self.act(self.wi_a(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = self.wi_a(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Optional[int] = self.dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.wo(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.ones(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = eps def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : str = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> torch.Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(__lowerCamelCase , 3.0 )) )) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Any = nn.Linear(__lowerCamelCase , out_features * 2 , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.scale_bias(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = torch.chunk(__lowerCamelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE : Optional[int] = x * (1 + scale) + shift return x
325
1
import argparse import os import torch from transformers.utils import WEIGHTS_NAME UpperCamelCase__ =['small', 'medium', 'large'] UpperCamelCase__ ='lm_head.decoder.weight' UpperCamelCase__ ='lm_head.weight' def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = torch.load(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = d.pop(__lowerCamelCase ) os.makedirs(__lowerCamelCase, exist_ok=__lowerCamelCase ) torch.save(__lowerCamelCase, os.path.join(__lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--dialogpt_path', default='.', type=str) UpperCamelCase__ =parser.parse_args() for MODEL in DIALOGPT_MODELS: UpperCamelCase__ =os.path.join(args.dialogpt_path, f"{MODEL}_ft.pkl") UpperCamelCase__ =f"./DialoGPT-{MODEL}" convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
325
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=__lowercase ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = field(default='audio-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) __snake_case = Features({'audio': Audio()} ) __snake_case = Features({'labels': ClassLabel} ) __snake_case = "audio" __snake_case = "labels" def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: if self.label_column not in features: raise ValueError(F"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""" ) _SCREAMING_SNAKE_CASE : Any = copy.deepcopy(self ) _SCREAMING_SNAKE_CASE : List[str] = self.label_schema.copy() _SCREAMING_SNAKE_CASE : Union[str, Any] = features[self.label_column] _SCREAMING_SNAKE_CASE : Union[str, Any] = label_schema return task_template @property def UpperCamelCase_ ( self ) -> Dict[str, str]: return { self.audio_column: "audio", self.label_column: "labels", }
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
import re from filelock import FileLock try: import nltk UpperCamelCase__ =True except (ImportError, ModuleNotFoundError): UpperCamelCase__ =False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase__ (__lowerCamelCase ): re.sub("<n>", "", __lowerCamelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__lowerCamelCase ) )
325
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'timesformer' def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> List[str]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = qkv_bias _SCREAMING_SNAKE_CASE : Tuple = attention_type _SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate
325
1
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer _SCREAMING_SNAKE_CASE : str = flax_key_tuple[:-1] + ("weight",) _SCREAMING_SNAKE_CASE : List[Any] = torch.permute(__lowerCamelCase, (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCamelCase ): # linear layer _SCREAMING_SNAKE_CASE : int = flax_key_tuple[:-1] + ("weight",) _SCREAMING_SNAKE_CASE : List[str] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: _SCREAMING_SNAKE_CASE : int = flax_key_tuple[:-1] + ("weight",) return flax_key_tuple, flax_tensor def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if "metadata" in layer: _SCREAMING_SNAKE_CASE : Dict = layer.split("metadata" ) _SCREAMING_SNAKE_CASE : str = "".join(split_layer[0] )[:-1] _SCREAMING_SNAKE_CASE : Any = [tuple(("metadata" + split_layer[1]).split("/" ) )] elif "kvstore" in layer: _SCREAMING_SNAKE_CASE : str = layer.split("kvstore" ) _SCREAMING_SNAKE_CASE : int = "".join(split_layer[0] )[:-1] _SCREAMING_SNAKE_CASE : Dict = [tuple(("kvstore" + split_layer[1]).split("/" ) )] else: _SCREAMING_SNAKE_CASE : str = layer.split("/" ) _SCREAMING_SNAKE_CASE : Tuple = "/".join(split_layer[:-1] ) _SCREAMING_SNAKE_CASE : Tuple = (split_layer[-1],) if "kvstore/path" in layer: _SCREAMING_SNAKE_CASE : List[str] = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: _SCREAMING_SNAKE_CASE : str = "file" else: _SCREAMING_SNAKE_CASE : Optional[Any] = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = rename_keys(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in current_block.items(): _SCREAMING_SNAKE_CASE : List[Any] = v _SCREAMING_SNAKE_CASE : int = new_current_block torch.save(__lowerCamelCase, __lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = WEIGHTS_NAME ): _SCREAMING_SNAKE_CASE : int = convert_file_size_to_int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = [] _SCREAMING_SNAKE_CASE : List[str] = {} _SCREAMING_SNAKE_CASE : Dict = 0 _SCREAMING_SNAKE_CASE : Dict = 0 os.makedirs(__lowerCamelCase, exist_ok=__lowerCamelCase ) with gfile.GFile(switch_checkpoint_path + "/checkpoint", "rb" ) as fp: _SCREAMING_SNAKE_CASE : str = serialization.msgpack_restore(fp.read() )["optimizer"]["target"] _SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(__lowerCamelCase, sep="/" ) _SCREAMING_SNAKE_CASE : List[Any] = {} for layer in checkpoint_info.keys(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = get_key_and_tensorstore_dict( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if curr_real_layer_name in all_layers: _SCREAMING_SNAKE_CASE : Dict = content else: _SCREAMING_SNAKE_CASE : int = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file _SCREAMING_SNAKE_CASE : Optional[Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = rename_base_flax_keys(tuple(key.split("/" ) ), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = "/".join(__lowerCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: _SCREAMING_SNAKE_CASE : Tuple = os.path.join( __lowerCamelCase, weights_name.replace(".bin", f"""-{len(__lowerCamelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__lowerCamelCase, __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block _SCREAMING_SNAKE_CASE : Tuple = {} _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = raw_weights.to(getattr(__lowerCamelCase, __lowerCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block _SCREAMING_SNAKE_CASE : List[Any] = os.path.join(__lowerCamelCase, weights_name.replace(".bin", f"""-{len(__lowerCamelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__lowerCamelCase, __lowerCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : Optional[int] = {} for idx, shard in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = weights_name.replace( ".bin", f"""-{idx+1:05d}-of-{len(__lowerCamelCase ):05d}.bin""" ) # len(sharded_state_dicts):05d} _SCREAMING_SNAKE_CASE : List[Any] = os.path.join(__lowerCamelCase, weights_name.replace(".bin", f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(__lowerCamelCase, os.path.join(__lowerCamelCase, __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = shard for key in shard: _SCREAMING_SNAKE_CASE : Any = shard_file # Add the metadata _SCREAMING_SNAKE_CASE : Optional[Any] = {"total_size": total_size} _SCREAMING_SNAKE_CASE : Any = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(__lowerCamelCase, __lowerCamelCase ), "w", encoding="utf-8" ) as f: _SCREAMING_SNAKE_CASE : str = json.dumps(__lowerCamelCase, indent=2, sort_keys=__lowerCamelCase ) + "\n" f.write(__lowerCamelCase ) return metadata, index if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) UpperCamelCase__ =parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def lowerCamelCase__ (): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer _SCREAMING_SNAKE_CASE : int = SwitchTransformersConfig.from_pretrained("google/switch-base-8" ) config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" ) _SCREAMING_SNAKE_CASE : Tuple = SwitchTransformersForConditionalGeneration.from_pretrained( "/home/arthur_huggingface_co/transformers/switch_converted", device_map="auto" ) _SCREAMING_SNAKE_CASE : Tuple = TaTokenizer.from_pretrained("t5-small" ) _SCREAMING_SNAKE_CASE : Tuple = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>." _SCREAMING_SNAKE_CASE : Any = tokenizer(__lowerCamelCase, return_tensors="pt" ).input_ids _SCREAMING_SNAKE_CASE : int = model.generate(__lowerCamelCase, decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="[CLS]" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<unk>" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<pad>" , __lowerCamelCase="[CLS]" , __lowerCamelCase="[MASK]" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _SCREAMING_SNAKE_CASE : List[Any] = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : str = keep_accents _SCREAMING_SNAKE_CASE : Optional[int] = vocab_file _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: if self.remove_space: _SCREAMING_SNAKE_CASE : List[str] = " ".join(inputs.strip().split() ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = inputs _SCREAMING_SNAKE_CASE : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: _SCREAMING_SNAKE_CASE : str = unicodedata.normalize("NFKD" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: _SCREAMING_SNAKE_CASE : Dict = outputs.lower() return outputs def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): _SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[1:] else: _SCREAMING_SNAKE_CASE : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[str] = "" _SCREAMING_SNAKE_CASE : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : List[Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'roformer' def __init__( self , __lowerCamelCase=5_0_0_0_0 , __lowerCamelCase=None , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=1_5_3_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-12 , __lowerCamelCase=0 , __lowerCamelCase=False , __lowerCamelCase=True , **__lowerCamelCase , ) -> Any: super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size if embedding_size is None else embedding_size _SCREAMING_SNAKE_CASE : List[Any] = hidden_size _SCREAMING_SNAKE_CASE : Dict = num_hidden_layers _SCREAMING_SNAKE_CASE : int = num_attention_heads _SCREAMING_SNAKE_CASE : List[str] = hidden_act _SCREAMING_SNAKE_CASE : int = intermediate_size _SCREAMING_SNAKE_CASE : str = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size _SCREAMING_SNAKE_CASE : Any = initializer_range _SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[Any] = rotary_value _SCREAMING_SNAKE_CASE : List[Any] = use_cache class lowerCAmelCase__( __lowercase ): '''simple docstring''' @property def UpperCamelCase_ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: _SCREAMING_SNAKE_CASE : List[str] = {0: "batch", 1: "sequence"} _SCREAMING_SNAKE_CASE : Tuple = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
325
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
1
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger UpperCamelCase__ =get_logger(__name__) class lowerCAmelCase__( enum.Enum ): '''simple docstring''' __snake_case = 'all_checks' __snake_case = 'basic_checks' __snake_case = 'no_checks' class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None ): if expected_checksums is None: logger.info("Unable to verify checksums." ) return if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) ) if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0: raise UnexpectedDownloadedFile(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) ) _SCREAMING_SNAKE_CASE : Dict = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _SCREAMING_SNAKE_CASE : List[str] = " for " + verification_name if verification_name is not None else "" if len(__lowerCamelCase ) > 0: raise NonMatchingChecksumError( f"""Checksums didn't match{for_verification_name}:\n""" f"""{bad_urls}\n""" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error" ) logger.info("All the checksums matched successfully" + for_verification_name ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' class lowerCAmelCase__( __lowercase ): '''simple docstring''' def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if expected_splits is None: logger.info("Unable to verify splits sizes." ) return if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0: raise ExpectedMoreSplits(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) ) if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0: raise UnexpectedSplits(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) ) _SCREAMING_SNAKE_CASE : int = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(__lowerCamelCase ) > 0: raise NonMatchingSplitsSizesError(str(__lowerCamelCase ) ) logger.info("All the splits matched successfully." ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase = True ): if record_checksum: _SCREAMING_SNAKE_CASE : int = shaaaa() with open(__lowerCamelCase, "rb" ) as f: for chunk in iter(lambda: f.read(1 << 20 ), B"" ): m.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = m.hexdigest() else: _SCREAMING_SNAKE_CASE : Dict = None return {"num_bytes": os.path.getsize(__lowerCamelCase ), "checksum": checksum} def lowerCamelCase__ (__lowerCamelCase ): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
325
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
1
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def lowerCamelCase__ (__lowerCamelCase="" ): _SCREAMING_SNAKE_CASE : Any = tempfile.mkdtemp() return os.path.join(__lowerCamelCase, str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : List[Any] = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 _SCREAMING_SNAKE_CASE : int = AgentAudio(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(__lowerCamelCase , agent_type.to_raw() , atol=1E-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(__lowerCamelCase ) ) # Ensure that the file contains the same value as the original tensor _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = sf.read(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , torch.tensor(__lowerCamelCase ) , atol=1E-4 ) ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 _SCREAMING_SNAKE_CASE : List[Any] = get_new_path(suffix=".wav" ) sf.write(__lowerCamelCase , __lowerCamelCase , 1_6_0_0_0 ) _SCREAMING_SNAKE_CASE : int = AgentAudio(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , agent_type.to_raw() , atol=1E-4 ) ) self.assertEqual(agent_type.to_string() , __lowerCamelCase ) @require_vision @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = torch.randint(0 , 2_5_6 , (6_4, 6_4, 3) ) _SCREAMING_SNAKE_CASE : int = AgentImage(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(__lowerCamelCase , agent_type._tensor , atol=1E-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(__lowerCamelCase ) ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" _SCREAMING_SNAKE_CASE : Any = Image.open(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = AgentImage(__lowerCamelCase ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(__lowerCamelCase ) ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Tuple = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" _SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = AgentImage(__lowerCamelCase ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(__lowerCamelCase ) ) class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = "Hey!" _SCREAMING_SNAKE_CASE : str = AgentText(__lowerCamelCase ) self.assertEqual(__lowerCamelCase , agent_type.to_string() ) self.assertEqual(__lowerCamelCase , agent_type.to_raw() ) self.assertEqual(__lowerCamelCase , __lowerCamelCase )
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=7 , __lowerCamelCase=3 , __lowerCamelCase=3_0 , __lowerCamelCase=4_0_0 , __lowerCamelCase=True , __lowerCamelCase=None , __lowerCamelCase=True , __lowerCamelCase=[0.5, 0.5, 0.5] , __lowerCamelCase=[0.5, 0.5, 0.5] , __lowerCamelCase=True , __lowerCamelCase=1 / 2_5_5 , __lowerCamelCase=True , ) -> Tuple: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _SCREAMING_SNAKE_CASE : Optional[int] = size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} _SCREAMING_SNAKE_CASE : Optional[int] = parent _SCREAMING_SNAKE_CASE : Optional[int] = batch_size _SCREAMING_SNAKE_CASE : Dict = num_channels _SCREAMING_SNAKE_CASE : Optional[Any] = min_resolution _SCREAMING_SNAKE_CASE : str = max_resolution _SCREAMING_SNAKE_CASE : str = do_resize _SCREAMING_SNAKE_CASE : Optional[Any] = size _SCREAMING_SNAKE_CASE : List[Any] = do_normalize _SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean _SCREAMING_SNAKE_CASE : Optional[Any] = image_std _SCREAMING_SNAKE_CASE : str = do_rescale _SCREAMING_SNAKE_CASE : Any = rescale_factor _SCREAMING_SNAKE_CASE : List[Any] = do_pad def UpperCamelCase_ ( self ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=False ) -> str: if not batched: _SCREAMING_SNAKE_CASE : Optional[Any] = image_inputs[0] if isinstance(__lowerCamelCase , Image.Image ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = image.size else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: _SCREAMING_SNAKE_CASE : int = int(self.size["shortest_edge"] * h / w ) _SCREAMING_SNAKE_CASE : str = self.size["shortest_edge"] elif w > h: _SCREAMING_SNAKE_CASE : int = self.size["shortest_edge"] _SCREAMING_SNAKE_CASE : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: _SCREAMING_SNAKE_CASE : Any = self.size["shortest_edge"] _SCREAMING_SNAKE_CASE : List[Any] = self.size["shortest_edge"] else: _SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _SCREAMING_SNAKE_CASE : Optional[int] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[0] )[0] _SCREAMING_SNAKE_CASE : List[str] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = DetaImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : str = DetaImageProcessingTester(self ) @property def UpperCamelCase_ ( self ) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(__lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_rescale" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(__lowerCamelCase , "size" ) ) def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: pass def UpperCamelCase_ ( self ) -> Any: # Initialize image_processing _SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> Tuple: # Initialize image_processing _SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input _SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE : Dict = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> Union[str, Any]: # Initialize image_processing _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE : Tuple = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCamelCase_ ( self ) -> List[str]: # prepare image and target _SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: _SCREAMING_SNAKE_CASE : Dict = json.loads(f.read() ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"image_id": 3_9_7_6_9, "annotations": target} # encode them _SCREAMING_SNAKE_CASE : int = DetaImageProcessor() _SCREAMING_SNAKE_CASE : List[Any] = image_processing(images=__lowerCamelCase , annotations=__lowerCamelCase , return_tensors="pt" ) # verify pixel values _SCREAMING_SNAKE_CASE : Tuple = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , __lowerCamelCase , atol=1E-4 ) ) # verify area _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , __lowerCamelCase ) ) # verify boxes _SCREAMING_SNAKE_CASE : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , __lowerCamelCase , atol=1E-3 ) ) # verify image_id _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , __lowerCamelCase ) ) # verify is_crowd _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , __lowerCamelCase ) ) # verify class_labels _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , __lowerCamelCase ) ) # verify orig_size _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , __lowerCamelCase ) ) # verify size _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , __lowerCamelCase ) ) @slow def UpperCamelCase_ ( self ) -> Union[str, Any]: # prepare image, target and masks_path _SCREAMING_SNAKE_CASE : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: _SCREAMING_SNAKE_CASE : Optional[int] = json.loads(f.read() ) _SCREAMING_SNAKE_CASE : int = {"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} _SCREAMING_SNAKE_CASE : List[str] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them _SCREAMING_SNAKE_CASE : Tuple = DetaImageProcessor(format="coco_panoptic" ) _SCREAMING_SNAKE_CASE : Tuple = image_processing(images=__lowerCamelCase , annotations=__lowerCamelCase , masks_path=__lowerCamelCase , return_tensors="pt" ) # verify pixel values _SCREAMING_SNAKE_CASE : Dict = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , __lowerCamelCase , atol=1E-4 ) ) # verify area _SCREAMING_SNAKE_CASE : List[str] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , __lowerCamelCase ) ) # verify boxes _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , __lowerCamelCase , atol=1E-3 ) ) # verify image_id _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , __lowerCamelCase ) ) # verify is_crowd _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , __lowerCamelCase ) ) # verify class_labels _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , __lowerCamelCase ) ) # verify masks _SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , __lowerCamelCase ) # verify orig_size _SCREAMING_SNAKE_CASE : int = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , __lowerCamelCase ) ) # verify size _SCREAMING_SNAKE_CASE : int = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , __lowerCamelCase ) )
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=1_0 , __lowerCamelCase=3 , __lowerCamelCase=2 , __lowerCamelCase=2 , __lowerCamelCase=2 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=3_2 , __lowerCamelCase=5 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=1_0 , __lowerCamelCase=0.02 , __lowerCamelCase=0.9 , __lowerCamelCase=None , ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = parent _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size _SCREAMING_SNAKE_CASE : List[Any] = image_size _SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels _SCREAMING_SNAKE_CASE : Dict = patch_size _SCREAMING_SNAKE_CASE : int = tubelet_size _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Optional[Any] = is_training _SCREAMING_SNAKE_CASE : Optional[int] = use_labels _SCREAMING_SNAKE_CASE : Optional[int] = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers _SCREAMING_SNAKE_CASE : Tuple = num_attention_heads _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : List[str] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size _SCREAMING_SNAKE_CASE : List[str] = initializer_range _SCREAMING_SNAKE_CASE : Dict = mask_ratio _SCREAMING_SNAKE_CASE : Any = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame _SCREAMING_SNAKE_CASE : List[Any] = (image_size // patch_size) ** 2 _SCREAMING_SNAKE_CASE : Union[str, Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos _SCREAMING_SNAKE_CASE : Dict = int(mask_ratio * self.seq_length ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE : Tuple = None if self.use_labels: _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : Any = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self ) -> Optional[Any]: return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = VideoMAEModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : str = VideoMAEForPreTraining(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch _SCREAMING_SNAKE_CASE : Optional[Any] = torch.ones((self.num_masks,) ) _SCREAMING_SNAKE_CASE : Dict = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) _SCREAMING_SNAKE_CASE : Dict = mask.expand(self.batch_size , -1 ).bool() _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase , __lowerCamelCase ) # model only returns predictions for masked patches _SCREAMING_SNAKE_CASE : List[str] = mask.sum().item() _SCREAMING_SNAKE_CASE : int = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Union[str, Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) __snake_case = ( {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification} if is_torch_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Tuple = VideoMAEModelTester(self ) _SCREAMING_SNAKE_CASE : Optional[int] = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False ) -> Optional[int]: _SCREAMING_SNAKE_CASE : List[Any] = copy.deepcopy(__lowerCamelCase ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch _SCREAMING_SNAKE_CASE : int = torch.ones((self.model_tester.num_masks,) ) _SCREAMING_SNAKE_CASE : Dict = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) _SCREAMING_SNAKE_CASE : str = mask.expand(self.model_tester.batch_size , -1 ).bool() _SCREAMING_SNAKE_CASE : List[Any] = bool_masked_pos.to(__lowerCamelCase ) if return_labels: if model_class in [ *get_values(__lowerCamelCase ), ]: _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase ) return inputs_dict def UpperCamelCase_ ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason="VideoMAE does not use inputs_embeds" ) def UpperCamelCase_ ( self ) -> str: pass def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _SCREAMING_SNAKE_CASE : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , nn.Linear ) ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : str = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> List[Any]: for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE : Optional[Any] = VideoMAEModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> str: if not self.has_attentions: pass else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.seq_length - self.model_tester.num_masks _SCREAMING_SNAKE_CASE : Optional[int] = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : Any = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Tuple = True _SCREAMING_SNAKE_CASE : Optional[Any] = True _SCREAMING_SNAKE_CASE : str = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Union[str, Any] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + 1 , len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = outputs.attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def UpperCamelCase_ ( self ) -> int: def check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = outputs.hidden_states _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.model_tester.seq_length - self.model_tester.num_masks _SCREAMING_SNAKE_CASE : Tuple = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : int = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : Dict = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCamelCase_ ( self ) -> str: pass def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset" ) _SCREAMING_SNAKE_CASE : List[str] = np.load(__lowerCamelCase ) return list(__lowerCamelCase ) @require_torch @require_vision class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self ) -> int: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : str = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics" ).to( __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.default_image_processor _SCREAMING_SNAKE_CASE : Optional[Any] = prepare_video() _SCREAMING_SNAKE_CASE : List[str] = image_processor(__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Tuple = model(**__lowerCamelCase ) # verify the logits _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 4_0_0) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0.3669, -0.0688, -0.2421] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short" ).to(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor _SCREAMING_SNAKE_CASE : List[Any] = prepare_video() _SCREAMING_SNAKE_CASE : Optional[int] = image_processor(__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # add boolean mask, indicating which patches to mask _SCREAMING_SNAKE_CASE : List[Any] = hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos" , filename="bool_masked_pos.pt" ) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.load(__lowerCamelCase ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : str = model(**__lowerCamelCase ) # verify the logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size([1, 1_4_0_8, 1_5_3_6] ) _SCREAMING_SNAKE_CASE : Any = torch.tensor( [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] , device=__lowerCamelCase ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , __lowerCamelCase , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([0.5142] , device=__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.loss , __lowerCamelCase , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) _SCREAMING_SNAKE_CASE : List[Any] = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short" , norm_pix_loss=__lowerCamelCase ).to( __lowerCamelCase ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : str = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = torch.tensor(torch.tensor([0.6469] ) , device=__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.loss , __lowerCamelCase , atol=1E-4 ) )
325
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = 1_3 _SCREAMING_SNAKE_CASE : List[str] = 7 _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : int = 9_9 _SCREAMING_SNAKE_CASE : str = 3_8_4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = 3_7 _SCREAMING_SNAKE_CASE : Union[str, Any] = "gelu" _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 _SCREAMING_SNAKE_CASE : Tuple = 1_6 _SCREAMING_SNAKE_CASE : Dict = 2 _SCREAMING_SNAKE_CASE : Any = 0.02 _SCREAMING_SNAKE_CASE : Any = 3 _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 1_2_8 _SCREAMING_SNAKE_CASE : Optional[int] = 2 _SCREAMING_SNAKE_CASE : int = 9 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = TFConvBertForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : str = TFConvBertForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_choices _SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = self.num_labels _SCREAMING_SNAKE_CASE : Tuple = TFConvBertForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : int = TFConvBertModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True if hasattr(__lowerCamelCase , "use_cache" ): _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = os.path.join(__lowerCamelCase , "saved_model" , "1" ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.models.load_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : List[Any] = outputs["encoder_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs["encoder_attentions"] else: _SCREAMING_SNAKE_CASE : List[str] = outputs["hidden_states"] _SCREAMING_SNAKE_CASE : Dict = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) _SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = [1, 6, 7_6_8] self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
325
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 lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = FunnelTokenizer __snake_case = FunnelTokenizerFast __snake_case = True __snake_case = True def UpperCamelCase_ ( self ) -> Dict: super().setUp() _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "<unk>", "<cls>", "<sep>", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self , **__lowerCamelCase ) -> int: return FunnelTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase_ ( self , **__lowerCamelCase ) -> int: return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = "UNwant\u00E9d,running" _SCREAMING_SNAKE_CASE : List[str] = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE : int = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(__lowerCamelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [7, 4, 5, 1_0, 8, 9] ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizers(do_lower_case=__lowerCamelCase ) for tokenizer in tokenizers: _SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("UNwant\u00E9d,running" ) _SCREAMING_SNAKE_CASE : Dict = len(inputs["input_ids"] ) - 1 self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len ) _SCREAMING_SNAKE_CASE : Any = tokenizer("UNwant\u00E9d,running" , "UNwant\u00E9d,running" ) self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len + [1] * sentence_len )
325
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
1
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase__ ={'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ =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). UpperCamelCase__ =[0, 25, 50] UpperCamelCase__ =[25, 50, 75] UpperCamelCase__ =fuzz.membership.trimf(X, abca) UpperCamelCase__ =fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCamelCase__ =np.ones(75) UpperCamelCase__ =np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCamelCase__ =fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCamelCase__ =young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCamelCase__ =young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCamelCase__ =fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCamelCase__ =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()
325
1
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase_ ( self ) -> List[Any]: torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE : Optional[int] = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.dummy_uncond_unet _SCREAMING_SNAKE_CASE : Optional[Any] = KarrasVeScheduler() _SCREAMING_SNAKE_CASE : Any = KarrasVePipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE : Any = pipe(num_inference_steps=2 , generator=__lowerCamelCase , output_type="numpy" ).images _SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE : int = pipe(num_inference_steps=2 , generator=__lowerCamelCase , output_type="numpy" , return_dict=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] _SCREAMING_SNAKE_CASE : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = "google/ncsnpp-celebahq-256" _SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = KarrasVeScheduler() _SCREAMING_SNAKE_CASE : List[Any] = KarrasVePipeline(unet=__lowerCamelCase , scheduler=__lowerCamelCase ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE : Tuple = pipe(num_inference_steps=2_0 , generator=__lowerCamelCase , output_type="numpy" ).images _SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) _SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
325
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
1
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , **__lowerCamelCase , ) -> str: super().__init__( features=__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase , streaming=__lowerCamelCase , num_proc=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Tuple = Generator( cache_dir=__lowerCamelCase , features=__lowerCamelCase , generator=__lowerCamelCase , gen_kwargs=__lowerCamelCase , **__lowerCamelCase , ) def UpperCamelCase_ ( self ) -> Dict: # Build iterable dataset if self.streaming: _SCREAMING_SNAKE_CASE : int = self.builder.as_streaming_dataset(split="train" ) # Build regular (map-style) dataset else: _SCREAMING_SNAKE_CASE : Any = None _SCREAMING_SNAKE_CASE : str = None _SCREAMING_SNAKE_CASE : str = None _SCREAMING_SNAKE_CASE : List[str] = None self.builder.download_and_prepare( download_config=__lowerCamelCase , download_mode=__lowerCamelCase , verification_mode=__lowerCamelCase , base_path=__lowerCamelCase , num_proc=self.num_proc , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.builder.as_dataset( split="train" , verification_mode=__lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
325
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lowerCamelCase, max_perimeter + 1 ): _SCREAMING_SNAKE_CASE : List[Any] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase__ (__lowerCamelCase = 1000 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = pythagorean_triple(__lowerCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
325
1
from numpy import exp, pi, sqrt def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase = 0.0, __lowerCamelCase = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
325
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # ===== initialization ===== _SCREAMING_SNAKE_CASE : List[Any] = Mock() _SCREAMING_SNAKE_CASE : Optional[Any] = conn, Mock() _SCREAMING_SNAKE_CASE : Dict = iter([1, None] ) _SCREAMING_SNAKE_CASE : Optional[Any] = lambda __lowerCamelCase : next(__lowerCamelCase ) # ===== invoke ===== send_file(filename="mytext.txt", testing=__lowerCamelCase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
325
1
from collections.abc import Iterable from typing import Any class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase = None ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[Any] = value _SCREAMING_SNAKE_CASE : Node | None = None # Added in order to delete a node easier _SCREAMING_SNAKE_CASE : Node | None = None _SCREAMING_SNAKE_CASE : Node | None = None def __repr__( self ) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase = None ) -> Dict: _SCREAMING_SNAKE_CASE : Tuple = root def __str__( self ) -> str: return str(self.root ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> None: if new_children is not None: # reset its kids _SCREAMING_SNAKE_CASE : List[str] = node.parent if node.parent is not None: # reset its parent if self.is_right(__lowerCamelCase ): # If it is the right children _SCREAMING_SNAKE_CASE : Union[str, Any] = new_children else: _SCREAMING_SNAKE_CASE : Union[str, Any] = new_children else: _SCREAMING_SNAKE_CASE : int = new_children def UpperCamelCase_ ( self , __lowerCamelCase ) -> bool: if node.parent and node.parent.right: return node == node.parent.right return False def UpperCamelCase_ ( self ) -> bool: return self.root is None def UpperCamelCase_ ( self , __lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Union[str, Any] = Node(__lowerCamelCase ) # create a new Node if self.empty(): # if Tree is empty _SCREAMING_SNAKE_CASE : List[str] = new_node # set its root else: # Tree is not empty _SCREAMING_SNAKE_CASE : Optional[int] = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: _SCREAMING_SNAKE_CASE : int = new_node # We insert the new node in a leaf break else: _SCREAMING_SNAKE_CASE : Optional[int] = parent_node.left else: if parent_node.right is None: _SCREAMING_SNAKE_CASE : Tuple = new_node break else: _SCREAMING_SNAKE_CASE : Union[str, Any] = parent_node.right _SCREAMING_SNAKE_CASE : str = parent_node def UpperCamelCase_ ( self , *__lowerCamelCase ) -> None: for value in values: self.__insert(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Node | None: if self.empty(): raise IndexError("Warning: Tree is empty! please use another." ) else: _SCREAMING_SNAKE_CASE : List[Any] = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: _SCREAMING_SNAKE_CASE : Dict = node.left if value < node.value else node.right return node def UpperCamelCase_ ( self , __lowerCamelCase = None ) -> Node | None: if node is None: if self.root is None: return None _SCREAMING_SNAKE_CASE : Tuple = self.root if not self.empty(): while node.right is not None: _SCREAMING_SNAKE_CASE : int = node.right return node def UpperCamelCase_ ( self , __lowerCamelCase = None ) -> Node | None: if node is None: _SCREAMING_SNAKE_CASE : List[str] = self.root if self.root is None: return None if not self.empty(): _SCREAMING_SNAKE_CASE : Tuple = self.root while node.left is not None: _SCREAMING_SNAKE_CASE : Dict = node.left return node def UpperCamelCase_ ( self , __lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Optional[int] = self.search(__lowerCamelCase ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__lowerCamelCase , __lowerCamelCase ) elif node.left is None: # Has only right children self.__reassign_nodes(__lowerCamelCase , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__lowerCamelCase , node.left ) else: _SCREAMING_SNAKE_CASE : int = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore _SCREAMING_SNAKE_CASE : int = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCamelCase_ ( self , __lowerCamelCase ) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCamelCase_ ( self , __lowerCamelCase=None ) -> Any: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> None: if node: self.inorder(__lowerCamelCase , node.left ) arr.append(node.value ) self.inorder(__lowerCamelCase , node.right ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : list[int] = [] self.inorder(__lowerCamelCase , __lowerCamelCase ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = [] if curr_node is not None: _SCREAMING_SNAKE_CASE : str = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Optional[int] = (8, 3, 6, 1, 10, 14, 13, 4, 7) _SCREAMING_SNAKE_CASE : int = BinarySearchTree() for i in testlist: t.insert(__lowerCamelCase ) # Prints all the elements of the list in order traversal print(__lowerCamelCase ) if t.search(6 ) is not None: print("The value 6 exists" ) else: print("The value 6 doesn't exist" ) if t.search(-1 ) is not None: print("The value -1 exists" ) else: print("The value -1 doesn't exist" ) if not t.empty(): print("Max Value: ", t.get_max().value ) # type: ignore print("Min Value: ", t.get_min().value ) # type: ignore for i in testlist: t.remove(__lowerCamelCase ) print(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
325
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['image_processor', 'tokenizer'] __snake_case = 'BlipImageProcessor' __snake_case = 'AutoTokenizer' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE : List[str] = qformer_tokenizer def __call__( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE : Any = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) encoding.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.qformer_tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : str = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE : List[Any] = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) encoding.update(__lowerCamelCase ) return encoding def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Union[str, Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> str: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> Any: if os.path.isfile(__lowerCamelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(__lowerCamelCase ) return super().save_pretrained(__lowerCamelCase , **__lowerCamelCase ) @classmethod def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(__lowerCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_arguments_from_pretrained(__lowerCamelCase , **__lowerCamelCase ) args.append(__lowerCamelCase ) return cls(*__lowerCamelCase )
325
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=3 , __lowerCamelCase=3_2 , __lowerCamelCase=3 , __lowerCamelCase=1_0 , __lowerCamelCase=[1_0, 2_0, 3_0, 4_0] , __lowerCamelCase=[1, 1, 2, 1] , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase="relu" , __lowerCamelCase=3 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : Any = parent _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size _SCREAMING_SNAKE_CASE : Dict = image_size _SCREAMING_SNAKE_CASE : Optional[Any] = num_channels _SCREAMING_SNAKE_CASE : Optional[Any] = embeddings_size _SCREAMING_SNAKE_CASE : Any = hidden_sizes _SCREAMING_SNAKE_CASE : Optional[int] = depths _SCREAMING_SNAKE_CASE : Any = is_training _SCREAMING_SNAKE_CASE : Optional[Any] = use_labels _SCREAMING_SNAKE_CASE : List[str] = hidden_act _SCREAMING_SNAKE_CASE : Union[str, Any] = num_labels _SCREAMING_SNAKE_CASE : str = scope _SCREAMING_SNAKE_CASE : Optional[Any] = len(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE : Any = self.get_config() return config, pixel_values def UpperCamelCase_ ( self ) -> Dict: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : str = FlaxRegNetModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels _SCREAMING_SNAKE_CASE : List[Any] = FlaxRegNetForImageClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs _SCREAMING_SNAKE_CASE : Tuple = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> None: _SCREAMING_SNAKE_CASE : Dict = FlaxRegNetModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase_ ( self ) -> int: return def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def UpperCamelCase_ ( self ) -> Optional[Any]: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def UpperCamelCase_ ( self ) -> int: pass def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: def check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _SCREAMING_SNAKE_CASE : int = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : List[str] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase , **__lowerCamelCase ): return model(pixel_values=__lowerCamelCase , **__lowerCamelCase ) with self.subTest("JIT Enabled" ): _SCREAMING_SNAKE_CASE : List[Any] = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): _SCREAMING_SNAKE_CASE : Optional[int] = model_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self ) -> List[str]: return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) _SCREAMING_SNAKE_CASE : List[str] = self.default_image_processor _SCREAMING_SNAKE_CASE : Tuple = prepare_img() _SCREAMING_SNAKE_CASE : int = image_processor(images=__lowerCamelCase , return_tensors="np" ) _SCREAMING_SNAKE_CASE : List[Any] = model(**__lowerCamelCase ) # verify the logits _SCREAMING_SNAKE_CASE : List[Any] = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) )
325
from maths.prime_check import is_prime def lowerCamelCase__ (__lowerCamelCase ): if not isinstance(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(__lowerCamelCase ) if is_prime(__lowerCamelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
325
1
from math import isqrt def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 10**8 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = calculate_prime_numbers(max_number // 2 ) _SCREAMING_SNAKE_CASE : Any = 0 _SCREAMING_SNAKE_CASE : List[Any] = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = len(__lowerCamelCase ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"{solution() = }")
325
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCamelCase__ (__lowerCamelCase ): return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = parser.add_parser("download" ) download_parser.add_argument( "--cache-dir" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to location to store the models" ) download_parser.add_argument( "--force" , action="store_true" , help="Force the model to be download even if already in cache-dir" ) download_parser.add_argument( "--trust-remote-code" , action="store_true" , help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine" , ) download_parser.add_argument("model" , type=__lowerCamelCase , help="Name of the model to download" ) download_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Any = model _SCREAMING_SNAKE_CASE : Optional[int] = cache _SCREAMING_SNAKE_CASE : str = force _SCREAMING_SNAKE_CASE : str = trust_remote_code def UpperCamelCase_ ( self ) -> Optional[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
325
1
from collections import defaultdict from math import gcd def lowerCamelCase__ (__lowerCamelCase = 1500000 ): _SCREAMING_SNAKE_CASE : defaultdict = defaultdict(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, __lowerCamelCase, 2 ): if gcd(__lowerCamelCase, __lowerCamelCase ) > 1: continue _SCREAMING_SNAKE_CASE : List[str] = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(__lowerCamelCase, limit + 1, __lowerCamelCase ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(f"{solution() = }")
325
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCAmelCase__: '''simple docstring''' __snake_case = BlenderbotSmallConfig __snake_case = {} __snake_case = 'gelu' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=2_0 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=0 , ) -> List[str]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Tuple = batch_size _SCREAMING_SNAKE_CASE : Dict = seq_length _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : int = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings _SCREAMING_SNAKE_CASE : Optional[int] = eos_token_id _SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id _SCREAMING_SNAKE_CASE : List[str] = bos_token_id def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _SCREAMING_SNAKE_CASE : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : str = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_small_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = TFBlenderbotSmallModel(config=__lowerCamelCase ).get_decoder() _SCREAMING_SNAKE_CASE : Dict = inputs_dict["input_ids"] _SCREAMING_SNAKE_CASE : List[Any] = input_ids[:1, :] _SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict["attention_mask"][:1, :] _SCREAMING_SNAKE_CASE : List[str] = inputs_dict["head_mask"] _SCREAMING_SNAKE_CASE : int = 1 # first forward pass _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _SCREAMING_SNAKE_CASE : Tuple = tf.concat([input_ids, next_tokens] , axis=-1 ) _SCREAMING_SNAKE_CASE : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _SCREAMING_SNAKE_CASE : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] _SCREAMING_SNAKE_CASE : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1E-3 ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, ): if attention_mask is None: _SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast(tf.math.not_equal(__lowerCamelCase, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ), ], axis=-1, ) if head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __snake_case = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __snake_case = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFBlenderbotSmallModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) @require_tokenizers @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' __snake_case = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __snake_case = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase_ ( self ) -> List[Any]: # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(self.src_text , return_tensors="tf" ) _SCREAMING_SNAKE_CASE : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCamelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
325
1
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'EncodecFeatureExtractor' __snake_case = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extractor _SCREAMING_SNAKE_CASE : Any = False def UpperCamelCase_ ( self , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=True ) -> Optional[int]: return self.tokenizer.get_decoder_prompt_ids(task=__lowerCamelCase , language=__lowerCamelCase , no_timestamps=__lowerCamelCase ) def __call__( self , *__lowerCamelCase , **__lowerCamelCase ) -> Optional[int]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = kwargs.pop("audio" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = kwargs.pop("sampling_rate" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop("text" , __lowerCamelCase ) if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : List[str] = args[0] _SCREAMING_SNAKE_CASE : Optional[Any] = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if text is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer(__lowerCamelCase , **__lowerCamelCase ) if audio is not None: _SCREAMING_SNAKE_CASE : Any = self.feature_extractor(__lowerCamelCase , *__lowerCamelCase , sampling_rate=__lowerCamelCase , **__lowerCamelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: _SCREAMING_SNAKE_CASE : Any = audio_inputs["input_values"] if "padding_mask" in audio_inputs: _SCREAMING_SNAKE_CASE : int = audio_inputs["padding_mask"] return inputs def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Any = kwargs.pop("audio" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = kwargs.pop("padding_mask" , __lowerCamelCase ) if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : List[str] = args[0] _SCREAMING_SNAKE_CASE : Any = args[1:] if audio_values is not None: return self._decode_audio(__lowerCamelCase , padding_mask=__lowerCamelCase ) else: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[np.ndarray]: _SCREAMING_SNAKE_CASE : Union[str, Any] = to_numpy(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = audio_values.shape if padding_mask is None: return list(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = to_numpy(__lowerCamelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) _SCREAMING_SNAKE_CASE : Dict = seq_len - padding_mask.shape[-1] _SCREAMING_SNAKE_CASE : Dict = 1 - self.feature_extractor.padding_value _SCREAMING_SNAKE_CASE : Union[str, Any] = np.pad(__lowerCamelCase , ((0, 0), (0, difference)) , "constant" , constant_values=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = audio_values.tolist() for i in range(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] _SCREAMING_SNAKE_CASE : Optional[Any] = sliced_audio.reshape(__lowerCamelCase , -1 ) return audio_values
325
from math import isqrt, loga def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 800800, __lowerCamelCase = 800800 ): _SCREAMING_SNAKE_CASE : Optional[int] = degree * loga(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = calculate_prime_numbers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
325
1
class lowerCAmelCase__: '''simple docstring''' def __init__( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = "" _SCREAMING_SNAKE_CASE : Dict = "" _SCREAMING_SNAKE_CASE : Optional[int] = [] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: _SCREAMING_SNAKE_CASE : Any = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: _SCREAMING_SNAKE_CASE : Dict = self.__min_dist_top_down_dp(__lowerCamelCase , n - 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) _SCREAMING_SNAKE_CASE : Tuple = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return self.dp[m][n] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = worda _SCREAMING_SNAKE_CASE : Dict = worda _SCREAMING_SNAKE_CASE : str = [[-1 for _ in range(len(__lowerCamelCase ) )] for _ in range(len(__lowerCamelCase ) )] return self.__min_dist_top_down_dp(len(__lowerCamelCase ) - 1 , len(__lowerCamelCase ) - 1 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : int = worda _SCREAMING_SNAKE_CASE : Optional[Any] = worda _SCREAMING_SNAKE_CASE : List[str] = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty _SCREAMING_SNAKE_CASE : Union[str, Any] = j elif j == 0: # second string is empty _SCREAMING_SNAKE_CASE : Optional[int] = i elif worda[i - 1] == worda[j - 1]: # last characters are equal _SCREAMING_SNAKE_CASE : Dict = self.dp[i - 1][j - 1] else: _SCREAMING_SNAKE_CASE : List[Any] = self.dp[i][j - 1] _SCREAMING_SNAKE_CASE : List[str] = self.dp[i - 1][j] _SCREAMING_SNAKE_CASE : Dict = self.dp[i - 1][j - 1] _SCREAMING_SNAKE_CASE : List[Any] = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return self.dp[m][n] if __name__ == "__main__": UpperCamelCase__ =EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() UpperCamelCase__ =input('Enter the first string: ').strip() UpperCamelCase__ =input('Enter the second string: ').strip() print() print(f"The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}") print(f"The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}") print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
325
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(__lowerCamelCase ) // (factorial(__lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( 'If a class of 40 students must be arranged into groups of', f"4 for group projects, there are {combinations(40, 4)} ways", 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f"are {combinations(10, 3)} ways that first, second and", 'third place can be awarded.', )
325
1
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase__: '''simple docstring''' @property def UpperCamelCase_ ( self ) -> List[Any]: return self.get_dummy_input() @property def UpperCamelCase_ ( self ) -> Any: if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : Optional[int] = 3_2 _SCREAMING_SNAKE_CASE : List[str] = (3_2, 3_2) _SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE : int = torch.device(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = (batch_size, num_channels) + sizes _SCREAMING_SNAKE_CASE : List[str] = randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = {"hidden_states": hidden_states} if include_temb: _SCREAMING_SNAKE_CASE : Tuple = 1_2_8 _SCREAMING_SNAKE_CASE : Tuple = randn_tensor((batch_size, temb_channels) , generator=__lowerCamelCase , device=__lowerCamelCase ) if include_res_hidden_states_tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(1 ) _SCREAMING_SNAKE_CASE : Optional[int] = (randn_tensor(__lowerCamelCase , generator=__lowerCamelCase , device=__lowerCamelCase ),) if include_encoder_hidden_states: _SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((batch_size, 3_2, 3_2) ).to(__lowerCamelCase ) if include_skip_sample: _SCREAMING_SNAKE_CASE : Dict = randn_tensor(((batch_size, 3) + sizes) , generator=__lowerCamelCase , device=__lowerCamelCase ) return dummy_input def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[Any] = { "in_channels": 3_2, "out_channels": 3_2, "temb_channels": 1_2_8, } if self.block_type == "up": _SCREAMING_SNAKE_CASE : str = 3_2 if self.block_type == "mid": init_dict.pop("out_channels" ) _SCREAMING_SNAKE_CASE : Dict = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self.prepare_init_args_and_inputs_for_common() _SCREAMING_SNAKE_CASE : List[str] = self.block_class(**__lowerCamelCase ) unet_block.to(__lowerCamelCase ) unet_block.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[str] = unet_block(**__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = output[0] self.assertEqual(output.shape , self.output_shape ) _SCREAMING_SNAKE_CASE : Optional[Any] = output[0, -1, -3:, -3:] _SCREAMING_SNAKE_CASE : Tuple = torch.tensor(__lowerCamelCase ).to(__lowerCamelCase ) assert torch_all_close(output_slice.flatten() , __lowerCamelCase , atol=5E-3 ) @unittest.skipIf(torch_device == "mps" , "Training is not supported in mps" ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.prepare_init_args_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = self.block_class(**__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() _SCREAMING_SNAKE_CASE : str = model(**__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = output[0] _SCREAMING_SNAKE_CASE : Optional[Any] = torch.device(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = randn_tensor(output.shape , device=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = torch.nn.functional.mse_loss(__lowerCamelCase , __lowerCamelCase ) loss.backward()
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 1_2_8 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 2000.0 , __lowerCamelCase = 7_6_8 , __lowerCamelCase = 1_2 , __lowerCamelCase = 1_2 , __lowerCamelCase = 6_4 , __lowerCamelCase = 2_0_4_8 , __lowerCamelCase = 0.1 , ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential( nn.Linear(__lowerCamelCase , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : str = nn.Embedding(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() for lyr_num in range(__lowerCamelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Optional[int] = DecoderLayer(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) self.decoders.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(__lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : Optional[int] = torch.broadcast_to( torch.arange(__lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.position_encoding(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.continuous_inputs_projection(__lowerCamelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Any = self.dropout(__lowerCamelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Any = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : List[str] = [(x, self.encoder_decoder_mask(__lowerCamelCase , __lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : Tuple = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Optional[Any] = lyr( __lowerCamelCase , conditioning_emb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , )[0] _SCREAMING_SNAKE_CASE : int = self.decoder_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.spec_out(__lowerCamelCase ) return spec_out class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.layer[0]( __lowerCamelCase , conditioning_emb=__lowerCamelCase , attention_mask=__lowerCamelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : str = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : Tuple = self.layer[1]( __lowerCamelCase , key_value_states=__lowerCamelCase , attention_mask=__lowerCamelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer[-1](__lowerCamelCase , __lowerCamelCase ) return (hidden_states,) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: # pre_self_attention_layer_norm _SCREAMING_SNAKE_CASE : int = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Any = self.FiLMLayer(__lowerCamelCase , __lowerCamelCase ) # Self-attention block _SCREAMING_SNAKE_CASE : Optional[int] = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.attention( __lowerCamelCase , encoder_hidden_states=__lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.dropout(__lowerCamelCase ) return layer_output class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.film(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.DenseReluDense(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = NewGELUActivation() def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Dict = self.act(self.wi_a(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = self.wi_a(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Optional[int] = self.dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.wo(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.ones(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = eps def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : str = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> torch.Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(__lowerCamelCase , 3.0 )) )) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Any = nn.Linear(__lowerCamelCase , out_features * 2 , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.scale_bias(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = torch.chunk(__lowerCamelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE : Optional[int] = x * (1 + scale) + shift return x
325
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ ={ 'configuration_roberta': ['ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaConfig', 'RobertaOnnxConfig'], 'tokenization_roberta': ['RobertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['RobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaForCausalLM', 'RobertaForMaskedLM', 'RobertaForMultipleChoice', 'RobertaForQuestionAnswering', 'RobertaForSequenceClassification', 'RobertaForTokenClassification', 'RobertaModel', 'RobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaForCausalLM', 'TFRobertaForMaskedLM', 'TFRobertaForMultipleChoice', 'TFRobertaForQuestionAnswering', 'TFRobertaForSequenceClassification', 'TFRobertaForTokenClassification', 'TFRobertaMainLayer', 'TFRobertaModel', 'TFRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'FlaxRobertaForCausalLM', 'FlaxRobertaForMaskedLM', 'FlaxRobertaForMultipleChoice', 'FlaxRobertaForQuestionAnswering', 'FlaxRobertaForSequenceClassification', 'FlaxRobertaForTokenClassification', 'FlaxRobertaModel', 'FlaxRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=5 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=4 , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = parent _SCREAMING_SNAKE_CASE : Optional[int] = batch_size _SCREAMING_SNAKE_CASE : List[Any] = seq_length _SCREAMING_SNAKE_CASE : Dict = is_training _SCREAMING_SNAKE_CASE : List[str] = use_attention_mask _SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids _SCREAMING_SNAKE_CASE : Any = use_labels _SCREAMING_SNAKE_CASE : List[Any] = vocab_size _SCREAMING_SNAKE_CASE : List[str] = hidden_size _SCREAMING_SNAKE_CASE : int = num_hidden_layers _SCREAMING_SNAKE_CASE : Any = num_attention_heads _SCREAMING_SNAKE_CASE : Any = intermediate_size _SCREAMING_SNAKE_CASE : Any = hidden_act _SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : Any = type_vocab_size _SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size _SCREAMING_SNAKE_CASE : Optional[int] = initializer_range _SCREAMING_SNAKE_CASE : int = num_choices def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Any = None if self.use_attention_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=__lowerCamelCase , ) return config, input_ids, attention_mask def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[int] = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Tuple = FlaxDistilBertModelTester(self ) @slow def UpperCamelCase_ ( self ) -> int: for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = model_class_name.from_pretrained("distilbert-base-uncased" ) _SCREAMING_SNAKE_CASE : Optional[int] = model(np.ones((1, 1) ) ) self.assertIsNotNone(__lowerCamelCase ) @require_flax class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Optional[int] = FlaxDistilBertModel.from_pretrained("distilbert-base-uncased" ) _SCREAMING_SNAKE_CASE : Any = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) _SCREAMING_SNAKE_CASE : str = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , __lowerCamelCase , atol=1E-4 ) )
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
from __future__ import annotations def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if nth_term == "": return [""] _SCREAMING_SNAKE_CASE : Optional[int] = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : list[str] = [] for temp in range(int(__lowerCamelCase ) ): series.append(f"""1 / {pow(temp + 1, int(__lowerCamelCase ) )}""" if series else "1" ) return series if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ =int(input('Enter the last number (nth term) of the P-Series')) UpperCamelCase__ =int(input('Enter the power for P-Series')) print('Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p') print(p_series(nth_term, power))
325
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'timesformer' def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> List[str]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = qkv_bias _SCREAMING_SNAKE_CASE : Tuple = attention_type _SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate
325
1
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ =OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCamelCase__ =OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCamelCase__ =OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCamelCase__ =OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCamelCase__ =OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCamelCase__ =OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCamelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModel) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCamelCase__ =auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class lowerCAmelCase__( _BaseAutoModelClass ): '''simple docstring''' __snake_case = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCamelCase__ =auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="[CLS]" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<unk>" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<pad>" , __lowerCamelCase="[CLS]" , __lowerCamelCase="[MASK]" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _SCREAMING_SNAKE_CASE : List[Any] = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : str = keep_accents _SCREAMING_SNAKE_CASE : Optional[int] = vocab_file _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: if self.remove_space: _SCREAMING_SNAKE_CASE : List[str] = " ".join(inputs.strip().split() ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = inputs _SCREAMING_SNAKE_CASE : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: _SCREAMING_SNAKE_CASE : str = unicodedata.normalize("NFKD" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: _SCREAMING_SNAKE_CASE : Dict = outputs.lower() return outputs def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): _SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[1:] else: _SCREAMING_SNAKE_CASE : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[str] = "" _SCREAMING_SNAKE_CASE : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : List[Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ ={ 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if index == r: for j in range(__lowerCamelCase ): print(data[j], end=" " ) print(" " ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location _SCREAMING_SNAKE_CASE : Tuple = arr[i] combination_util(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, index + 1, __lowerCamelCase, i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): # A temporary array to store all combination one by one _SCREAMING_SNAKE_CASE : Tuple = [0] * r # Print all combination using temporary array 'data[]' combination_util(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, 0, __lowerCamelCase, 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCamelCase__ =[10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
325
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
1
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
1
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(__lowerCamelCase ) // (factorial(__lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( 'If a class of 40 students must be arranged into groups of', f"4 for group projects, there are {combinations(40, 4)} ways", 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f"are {combinations(10, 3)} ways that first, second and", 'third place can be awarded.', )
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
1
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments UpperCamelCase__ =logging.getLogger(__name__) @dataclass class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = field( default=0.0 , metadata={'help': 'The label smoothing epsilon to apply (if not zero).'} ) __snake_case = field(default=__lowercase , metadata={'help': 'Whether to SortishSamler or not.'} ) __snake_case = field( default=__lowercase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} ) __snake_case = field(default=__lowercase , metadata={'help': 'whether to use adafactor'} ) __snake_case = field( default=__lowercase , metadata={'help': 'Encoder layer dropout probability. Goes into model.config.'} ) __snake_case = field( default=__lowercase , metadata={'help': 'Decoder layer dropout probability. Goes into model.config.'} ) __snake_case = field(default=__lowercase , metadata={'help': 'Dropout probability. Goes into model.config.'} ) __snake_case = field( default=__lowercase , metadata={'help': 'Attention dropout probability. Goes into model.config.'} ) __snake_case = field( default='linear' , metadata={'help': F"""Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"""} , )
325
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = 1_3 _SCREAMING_SNAKE_CASE : List[str] = 7 _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : int = 9_9 _SCREAMING_SNAKE_CASE : str = 3_8_4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = 3_7 _SCREAMING_SNAKE_CASE : Union[str, Any] = "gelu" _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 _SCREAMING_SNAKE_CASE : Tuple = 1_6 _SCREAMING_SNAKE_CASE : Dict = 2 _SCREAMING_SNAKE_CASE : Any = 0.02 _SCREAMING_SNAKE_CASE : Any = 3 _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 1_2_8 _SCREAMING_SNAKE_CASE : Optional[int] = 2 _SCREAMING_SNAKE_CASE : int = 9 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = TFConvBertForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : str = TFConvBertForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_choices _SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = self.num_labels _SCREAMING_SNAKE_CASE : Tuple = TFConvBertForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : int = TFConvBertModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True if hasattr(__lowerCamelCase , "use_cache" ): _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = os.path.join(__lowerCamelCase , "saved_model" , "1" ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.models.load_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : List[Any] = outputs["encoder_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs["encoder_attentions"] else: _SCREAMING_SNAKE_CASE : List[str] = outputs["hidden_states"] _SCREAMING_SNAKE_CASE : Dict = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) _SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = [1, 6, 7_6_8] self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : int = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) _SCREAMING_SNAKE_CASE : list = [] for char_count in range(__lowerCamelCase ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(__lowerCamelCase ) if __name__ == "__main__": print(alternative_string_arrange('AB', 'XYZ'), end=' ')
325
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
1
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCamelCase__ (__lowerCamelCase ): return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = parser.add_parser("download" ) download_parser.add_argument( "--cache-dir" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to location to store the models" ) download_parser.add_argument( "--force" , action="store_true" , help="Force the model to be download even if already in cache-dir" ) download_parser.add_argument( "--trust-remote-code" , action="store_true" , help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine" , ) download_parser.add_argument("model" , type=__lowerCamelCase , help="Name of the model to download" ) download_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Any = model _SCREAMING_SNAKE_CASE : Optional[int] = cache _SCREAMING_SNAKE_CASE : str = force _SCREAMING_SNAKE_CASE : str = trust_remote_code def UpperCamelCase_ ( self ) -> Optional[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
325
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'swin2sr' __snake_case = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , __lowerCamelCase=6_4 , __lowerCamelCase=1 , __lowerCamelCase=3 , __lowerCamelCase=1_8_0 , __lowerCamelCase=[6, 6, 6, 6, 6, 6] , __lowerCamelCase=[6, 6, 6, 6, 6, 6] , __lowerCamelCase=8 , __lowerCamelCase=2.0 , __lowerCamelCase=True , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.1 , __lowerCamelCase="gelu" , __lowerCamelCase=False , __lowerCamelCase=0.02 , __lowerCamelCase=1E-5 , __lowerCamelCase=2 , __lowerCamelCase=1.0 , __lowerCamelCase="1conv" , __lowerCamelCase="pixelshuffle" , **__lowerCamelCase , ) -> Union[str, Any]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : Any = patch_size _SCREAMING_SNAKE_CASE : Tuple = num_channels _SCREAMING_SNAKE_CASE : List[Any] = embed_dim _SCREAMING_SNAKE_CASE : Dict = depths _SCREAMING_SNAKE_CASE : Optional[int] = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = num_heads _SCREAMING_SNAKE_CASE : Union[str, Any] = window_size _SCREAMING_SNAKE_CASE : List[str] = mlp_ratio _SCREAMING_SNAKE_CASE : Union[str, Any] = qkv_bias _SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Tuple = drop_path_rate _SCREAMING_SNAKE_CASE : List[str] = hidden_act _SCREAMING_SNAKE_CASE : Optional[Any] = use_absolute_embeddings _SCREAMING_SNAKE_CASE : str = layer_norm_eps _SCREAMING_SNAKE_CASE : Dict = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = upscale _SCREAMING_SNAKE_CASE : int = img_range _SCREAMING_SNAKE_CASE : str = resi_connection _SCREAMING_SNAKE_CASE : Optional[Any] = upsampler
325
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ =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). UpperCamelCase__ =[0, 25, 50] UpperCamelCase__ =[25, 50, 75] UpperCamelCase__ =fuzz.membership.trimf(X, abca) UpperCamelCase__ =fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCamelCase__ =np.ones(75) UpperCamelCase__ =np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCamelCase__ =fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCamelCase__ =fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCamelCase__ =young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCamelCase__ =young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCamelCase__ =fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCamelCase__ =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()
325
1
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
1
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use BeitImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
from __future__ import annotations import typing from collections import Counter def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__lowerCamelCase, max_perimeter + 1 ): _SCREAMING_SNAKE_CASE : List[Any] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase__ (__lowerCamelCase = 1000 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = pythagorean_triple(__lowerCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
325
1
import requests from bsa import BeautifulSoup def lowerCamelCase__ (__lowerCamelCase = "https://www.worldometers.info/coronavirus" ): _SCREAMING_SNAKE_CASE : List[Any] = BeautifulSoup(requests.get(__lowerCamelCase ).text, "html.parser" ) _SCREAMING_SNAKE_CASE : List[Any] = soup.findAll("h1" ) _SCREAMING_SNAKE_CASE : Any = soup.findAll("div", {"class": "maincounter-number"} ) keys += soup.findAll("span", {"class": "panel-title"} ) values += soup.findAll("div", {"class": "number-table-main"} ) return {key.text.strip(): value.text.strip() for key, value in zip(__lowerCamelCase, __lowerCamelCase )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f"{key}\n{value}\n")
325
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # ===== initialization ===== _SCREAMING_SNAKE_CASE : List[Any] = Mock() _SCREAMING_SNAKE_CASE : Optional[Any] = conn, Mock() _SCREAMING_SNAKE_CASE : Dict = iter([1, None] ) _SCREAMING_SNAKE_CASE : Optional[Any] = lambda __lowerCamelCase : next(__lowerCamelCase ) # ===== invoke ===== send_file(filename="mytext.txt", testing=__lowerCamelCase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
325
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase=False ): if isinstance(__lowerCamelCase, __lowerCamelCase ) and isinstance(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = len(set_a.intersection(__lowerCamelCase ) ) if alternative_union: _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) + len(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE : Any = len(set_a.union(__lowerCamelCase ) ) return intersection / union if isinstance(__lowerCamelCase, (list, tuple) ) and isinstance(__lowerCamelCase, (list, tuple) ): _SCREAMING_SNAKE_CASE : str = [element for element in set_a if element in set_b] if alternative_union: _SCREAMING_SNAKE_CASE : Optional[int] = len(__lowerCamelCase ) + len(__lowerCamelCase ) return len(__lowerCamelCase ) / union else: _SCREAMING_SNAKE_CASE : Optional[int] = set_a + [element for element in set_b if element not in set_a] return len(__lowerCamelCase ) / len(__lowerCamelCase ) return len(__lowerCamelCase ) / len(__lowerCamelCase ) return None if __name__ == "__main__": UpperCamelCase__ ={'a', 'b', 'c', 'd', 'e'} UpperCamelCase__ ={'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
325
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['image_processor', 'tokenizer'] __snake_case = 'BlipImageProcessor' __snake_case = 'AutoTokenizer' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE : List[str] = qformer_tokenizer def __call__( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE : Any = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) encoding.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.qformer_tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : str = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE : List[Any] = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) encoding.update(__lowerCamelCase ) return encoding def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Union[str, Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> str: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> Any: if os.path.isfile(__lowerCamelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(__lowerCamelCase ) return super().save_pretrained(__lowerCamelCase , **__lowerCamelCase ) @classmethod def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(__lowerCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_arguments_from_pretrained(__lowerCamelCase , **__lowerCamelCase ) args.append(__lowerCamelCase ) return cls(*__lowerCamelCase )
325
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ ={ 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileBertConfig', 'MobileBertOnnxConfig', ], 'tokenization_mobilebert': ['MobileBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =['MobileBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileBertForMaskedLM', 'MobileBertForMultipleChoice', 'MobileBertForNextSentencePrediction', 'MobileBertForPreTraining', 'MobileBertForQuestionAnswering', 'MobileBertForSequenceClassification', 'MobileBertForTokenClassification', 'MobileBertLayer', 'MobileBertModel', 'MobileBertPreTrainedModel', 'load_tf_weights_in_mobilebert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileBertForMaskedLM', 'TFMobileBertForMultipleChoice', 'TFMobileBertForNextSentencePrediction', 'TFMobileBertForPreTraining', 'TFMobileBertForQuestionAnswering', 'TFMobileBertForSequenceClassification', 'TFMobileBertForTokenClassification', 'TFMobileBertMainLayer', 'TFMobileBertModel', 'TFMobileBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
from maths.prime_check import is_prime def lowerCamelCase__ (__lowerCamelCase ): if not isinstance(__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = f"""Input value of [number={number}] must be an integer""" raise TypeError(__lowerCamelCase ) if is_prime(__lowerCamelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
325
1
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed UpperCamelCase__ =logging.getLogger(__name__) def lowerCamelCase__ (__lowerCamelCase=2, __lowerCamelCase=3, __lowerCamelCase=16, __lowerCamelCase = 10, __lowerCamelCase = 2 ): def get_dataset(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = torch.randn(batch_size * n_batches, 1 ) return TensorDataset(__lowerCamelCase, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) ) _SCREAMING_SNAKE_CASE : Any = get_dataset(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = get_dataset(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader(__lowerCamelCase, shuffle=__lowerCamelCase, batch_size=__lowerCamelCase, num_workers=4 ) _SCREAMING_SNAKE_CASE : Any = DataLoader(__lowerCamelCase, shuffle=__lowerCamelCase, batch_size=__lowerCamelCase, num_workers=4 ) return (train_dataloader, valid_dataloader) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None ): _SCREAMING_SNAKE_CASE : Any = [] for epoch in range(__lowerCamelCase ): # Train quickly model.train() for batch in dataloader: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = batch _SCREAMING_SNAKE_CASE : Optional[int] = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = torch.nn.functional.mse_loss(__lowerCamelCase, __lowerCamelCase ) accelerator.backward(__lowerCamelCase ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(torch.randn(1 ) ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.randn(1 ) ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Tuple: return x * self.a + self.b class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) _SCREAMING_SNAKE_CASE : List[Any] = DummyModel() _SCREAMING_SNAKE_CASE : List[Any] = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = dummy_dataloaders() _SCREAMING_SNAKE_CASE : str = ProjectConfiguration(total_limit=1 , project_dir=__lowerCamelCase , automatic_checkpoint_naming=__lowerCamelCase ) # Train baseline _SCREAMING_SNAKE_CASE : Tuple = Accelerator(project_config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def UpperCamelCase_ ( self ) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) _SCREAMING_SNAKE_CASE : Tuple = DummyModel() _SCREAMING_SNAKE_CASE : Any = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = dummy_dataloaders() # Train baseline _SCREAMING_SNAKE_CASE : str = Accelerator() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save initial _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(__lowerCamelCase , "initial" ) accelerator.save_state(__lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Tuple = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : int = optimizer.state_dict() _SCREAMING_SNAKE_CASE : str = train(3 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : str = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : Optional[Any] = optimizer.state_dict() # Train partially set_seed(4_2 ) _SCREAMING_SNAKE_CASE : List[str] = DummyModel() _SCREAMING_SNAKE_CASE : Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = dummy_dataloaders() _SCREAMING_SNAKE_CASE : List[Any] = Accelerator() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) accelerator.load_state(__lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Tuple = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : Optional[int] = optimizer.state_dict() self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = train(2 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save everything _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "checkpoint" ) accelerator.save_state(__lowerCamelCase ) # Load everything back in and make sure all states work accelerator.load_state(__lowerCamelCase ) test_rands += train(1 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : List[Any] = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : Optional[int] = optimizer.state_dict() self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) _SCREAMING_SNAKE_CASE : int = DummyModel() _SCREAMING_SNAKE_CASE : Dict = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = dummy_dataloaders() _SCREAMING_SNAKE_CASE : List[str] = ProjectConfiguration(automatic_checkpoint_naming=__lowerCamelCase ) # Train baseline _SCREAMING_SNAKE_CASE : Any = Accelerator(project_dir=__lowerCamelCase , project_config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save initial accelerator.save_state() ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Optional[Any] = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : Union[str, Any] = optimizer.state_dict() _SCREAMING_SNAKE_CASE : Any = train(3 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Tuple = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : int = optimizer.state_dict() # Train partially set_seed(4_2 ) _SCREAMING_SNAKE_CASE : Dict = DummyModel() _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = dummy_dataloaders() _SCREAMING_SNAKE_CASE : Optional[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = Accelerator(project_dir=__lowerCamelCase , project_config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) accelerator.load_state(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_0" ) ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : Tuple = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : str = optimizer.state_dict() self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = train(2 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_1" ) ) test_rands += train(1 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) : str = model.a.item(), model.b.item() _SCREAMING_SNAKE_CASE : Union[str, Any] = optimizer.state_dict() self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([1, 2, 3] ) _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([2, 3, 4] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = DummyModel() _SCREAMING_SNAKE_CASE : Optional[Any] = torch.optim.Adam(net.parameters() ) _SCREAMING_SNAKE_CASE : Union[str, Any] = Accelerator() with self.assertRaises(__lowerCamelCase ) as ve: accelerator.register_for_checkpointing(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = str(ve.exception ) self.assertTrue("Item at index 0" in message ) self.assertTrue("Item at index 1" in message ) self.assertFalse("Item at index 2" in message ) self.assertFalse("Item at index 3" in message ) def UpperCamelCase_ ( self ) -> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) _SCREAMING_SNAKE_CASE : int = DummyModel() _SCREAMING_SNAKE_CASE : Optional[Any] = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) _SCREAMING_SNAKE_CASE : int = torch.optim.lr_scheduler.StepLR(__lowerCamelCase , step_size=1 , gamma=0.99 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = dummy_dataloaders() _SCREAMING_SNAKE_CASE : Any = ProjectConfiguration(automatic_checkpoint_naming=__lowerCamelCase ) # Train baseline _SCREAMING_SNAKE_CASE : List[Any] = Accelerator(project_dir=__lowerCamelCase , project_config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save initial accelerator.save_state() _SCREAMING_SNAKE_CASE : Dict = scheduler.state_dict() train(3 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) self.assertNotEqual(__lowerCamelCase , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_0" ) ) self.assertEqual(__lowerCamelCase , scheduler.state_dict() ) def UpperCamelCase_ ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) _SCREAMING_SNAKE_CASE : List[Any] = DummyModel() _SCREAMING_SNAKE_CASE : Any = ProjectConfiguration(automatic_checkpoint_naming=__lowerCamelCase , total_limit=2 ) # Train baseline _SCREAMING_SNAKE_CASE : Tuple = Accelerator(project_dir=__lowerCamelCase , project_config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = accelerator.prepare(__lowerCamelCase ) # Save 3 states: for _ in range(1_1 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_9" ) ) ) self.assertTrue(os.path.exists(os.path.join(__lowerCamelCase , "checkpoints" , "checkpoint_10" ) ) ) @require_cuda def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = ["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) if __name__ == "__main__": UpperCamelCase__ ='/tmp/accelerate/state_checkpointing' UpperCamelCase__ =DummyModel() UpperCamelCase__ =torch.optim.Adam(params=model.parameters(), lr=1E-3) UpperCamelCase__ =torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) UpperCamelCase__ , UpperCamelCase__ =dummy_dataloaders() UpperCamelCase__ =ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline UpperCamelCase__ =Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ =accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) UpperCamelCase__ , UpperCamelCase__ =accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: UpperCamelCase__ =group['params'][0].device break assert param_device.type == accelerator.device.type UpperCamelCase__ =model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: UpperCamelCase__ =group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: UpperCamelCase__ =group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
325
from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCamelCase__ (__lowerCamelCase ): return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = parser.add_parser("download" ) download_parser.add_argument( "--cache-dir" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to location to store the models" ) download_parser.add_argument( "--force" , action="store_true" , help="Force the model to be download even if already in cache-dir" ) download_parser.add_argument( "--trust-remote-code" , action="store_true" , help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine" , ) download_parser.add_argument("model" , type=__lowerCamelCase , help="Name of the model to download" ) download_parser.set_defaults(func=__lowerCamelCase ) def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : Any = model _SCREAMING_SNAKE_CASE : Optional[int] = cache _SCREAMING_SNAKE_CASE : str = force _SCREAMING_SNAKE_CASE : str = trust_remote_code def UpperCamelCase_ ( self ) -> Optional[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
325
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 lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = 384 _SCREAMING_SNAKE_CASE : int = 7 if "tiny" in model_name: _SCREAMING_SNAKE_CASE : Optional[Any] = 96 _SCREAMING_SNAKE_CASE : int = (2, 2, 6, 2) _SCREAMING_SNAKE_CASE : Union[str, Any] = (3, 6, 12, 24) elif "small" in model_name: _SCREAMING_SNAKE_CASE : Union[str, Any] = 96 _SCREAMING_SNAKE_CASE : str = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE : Optional[int] = (3, 6, 12, 24) elif "base" in model_name: _SCREAMING_SNAKE_CASE : Optional[Any] = 128 _SCREAMING_SNAKE_CASE : str = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE : Tuple = (4, 8, 16, 32) _SCREAMING_SNAKE_CASE : Optional[int] = 12 _SCREAMING_SNAKE_CASE : Union[str, Any] = 512 elif "large" in model_name: _SCREAMING_SNAKE_CASE : Tuple = 192 _SCREAMING_SNAKE_CASE : str = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE : int = (6, 12, 24, 48) _SCREAMING_SNAKE_CASE : str = 12 _SCREAMING_SNAKE_CASE : Tuple = 768 # set label information _SCREAMING_SNAKE_CASE : int = 150 _SCREAMING_SNAKE_CASE : str = "huggingface/label-files" _SCREAMING_SNAKE_CASE : Dict = "ade20k-id2label.json" _SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(__lowerCamelCase, __lowerCamelCase, repo_type="dataset" ), "r" ) ) _SCREAMING_SNAKE_CASE : Any = {int(__lowerCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : List[Any] = SwinConfig( embed_dim=__lowerCamelCase, depths=__lowerCamelCase, num_heads=__lowerCamelCase, window_size=__lowerCamelCase, out_features=["stage1", "stage2", "stage3", "stage4"], ) _SCREAMING_SNAKE_CASE : Tuple = UperNetConfig( backbone_config=__lowerCamelCase, auxiliary_in_channels=__lowerCamelCase, num_labels=__lowerCamelCase, idalabel=__lowerCamelCase, labelaid=__lowerCamelCase, ) return config def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [] # 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 lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = dct.pop(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): _SCREAMING_SNAKE_CASE : Any = 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) _SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight""" ) _SCREAMING_SNAKE_CASE : List[str] = 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 _SCREAMING_SNAKE_CASE : Any = in_proj_weight[:dim, :] _SCREAMING_SNAKE_CASE : str = in_proj_bias[: dim] _SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[ dim : dim * 2, : ] _SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[ dim : dim * 2 ] _SCREAMING_SNAKE_CASE : Dict = in_proj_weight[ -dim :, : ] _SCREAMING_SNAKE_CASE : Any = in_proj_bias[-dim :] # fmt: on def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = x.shape _SCREAMING_SNAKE_CASE : Dict = x.reshape(__lowerCamelCase, 4, in_channel // 4 ) _SCREAMING_SNAKE_CASE : List[str] = x[:, [0, 2, 1, 3], :].transpose(1, 2 ).reshape(__lowerCamelCase, __lowerCamelCase ) return x def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = x.shape _SCREAMING_SNAKE_CASE : int = x.reshape(__lowerCamelCase, in_channel // 4, 4 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = x[:, :, [0, 2, 1, 3]].transpose(1, 2 ).reshape(__lowerCamelCase, __lowerCamelCase ) return x def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = x.shape[0] _SCREAMING_SNAKE_CASE : str = x.reshape(4, in_channel // 4 ) _SCREAMING_SNAKE_CASE : Optional[int] = x[[0, 2, 1, 3], :].transpose(0, 1 ).reshape(__lowerCamelCase ) return x def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : str = x.shape[0] _SCREAMING_SNAKE_CASE : List[Any] = x.reshape(in_channel // 4, 4 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = x[:, [0, 2, 1, 3]].transpose(0, 1 ).reshape(__lowerCamelCase ) return x def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Dict = { "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", } _SCREAMING_SNAKE_CASE : Any = model_name_to_url[model_name] _SCREAMING_SNAKE_CASE : List[Any] = torch.hub.load_state_dict_from_url(__lowerCamelCase, map_location="cpu", file_name=__lowerCamelCase )[ "state_dict" ] for name, param in state_dict.items(): print(__lowerCamelCase, param.shape ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_upernet_config(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation(__lowerCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(__lowerCamelCase ) if "bn" in key: _SCREAMING_SNAKE_CASE : Dict = key.replace("bn", "batch_norm" ) _SCREAMING_SNAKE_CASE : Any = val # rename keys _SCREAMING_SNAKE_CASE : Optional[int] = create_rename_keys(__lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) read_in_q_k_v(__lowerCamelCase, config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: _SCREAMING_SNAKE_CASE : Union[str, Any] = reverse_correct_unfold_reduction_order(__lowerCamelCase ) if "norm" in key: _SCREAMING_SNAKE_CASE : List[Any] = reverse_correct_unfold_norm_order(__lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) # verify on image _SCREAMING_SNAKE_CASE : Union[str, Any] = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" _SCREAMING_SNAKE_CASE : str = Image.open(requests.get(__lowerCamelCase, stream=__lowerCamelCase ).raw ).convert("RGB" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = SegformerImageProcessor() _SCREAMING_SNAKE_CASE : List[str] = processor(__lowerCamelCase, return_tensors="pt" ).pixel_values with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = outputs.logits print(logits.shape ) print("First values of logits:", logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": _SCREAMING_SNAKE_CASE : List[str] = 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": _SCREAMING_SNAKE_CASE : List[str] = 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": _SCREAMING_SNAKE_CASE : Optional[int] = 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": _SCREAMING_SNAKE_CASE : Dict = 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], __lowerCamelCase, 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(__lowerCamelCase ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__lowerCamelCase ) 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__": UpperCamelCase__ =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.' ) UpperCamelCase__ =parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
325
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowerCAmelCase__: '''simple docstring''' __snake_case = BlenderbotSmallConfig __snake_case = {} __snake_case = 'gelu' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=2_0 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=0 , ) -> List[str]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Tuple = batch_size _SCREAMING_SNAKE_CASE : Dict = seq_length _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : List[str] = use_labels _SCREAMING_SNAKE_CASE : Dict = vocab_size _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : int = num_hidden_layers _SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob _SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings _SCREAMING_SNAKE_CASE : Optional[int] = eos_token_id _SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id _SCREAMING_SNAKE_CASE : List[str] = bos_token_id def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _SCREAMING_SNAKE_CASE : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : str = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_small_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Any = TFBlenderbotSmallModel(config=__lowerCamelCase ).get_decoder() _SCREAMING_SNAKE_CASE : Dict = inputs_dict["input_ids"] _SCREAMING_SNAKE_CASE : List[Any] = input_ids[:1, :] _SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict["attention_mask"][:1, :] _SCREAMING_SNAKE_CASE : List[str] = inputs_dict["head_mask"] _SCREAMING_SNAKE_CASE : int = 1 # first forward pass _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _SCREAMING_SNAKE_CASE : Tuple = tf.concat([input_ids, next_tokens] , axis=-1 ) _SCREAMING_SNAKE_CASE : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase , attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _SCREAMING_SNAKE_CASE : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _SCREAMING_SNAKE_CASE : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] _SCREAMING_SNAKE_CASE : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__lowerCamelCase , __lowerCamelCase , rtol=1E-3 ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, ): if attention_mask is None: _SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast(tf.math.not_equal(__lowerCamelCase, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ), ], axis=-1, ) if head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __snake_case = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __snake_case = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = TFBlenderbotSmallModelTester(self ) _SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) @require_tokenizers @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' __snake_case = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __snake_case = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase_ ( self ) -> List[Any]: # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(self.src_text , return_tensors="tf" ) _SCREAMING_SNAKE_CASE : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCamelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
325
1
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['input_ids', 'attention_mask'] def __init__( self , __lowerCamelCase , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: _SCREAMING_SNAKE_CASE : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs _SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) _SCREAMING_SNAKE_CASE : List[str] = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing _SCREAMING_SNAKE_CASE : Tuple = "<|endoftext|>" if eos_token is None else eos_token _SCREAMING_SNAKE_CASE : Any = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: _SCREAMING_SNAKE_CASE : Any = unk_token if pad_token is None else pad_token _SCREAMING_SNAKE_CASE : str = eos_token if bos_token is None else bos_token else: _SCREAMING_SNAKE_CASE : Union[str, Any] = "<pad>" if pad_token is None else pad_token _SCREAMING_SNAKE_CASE : str = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : Union[str, Any] = keep_accents _SCREAMING_SNAKE_CASE : List[Any] = vocab_file _SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) # Used for whitespace normalization in input texts # fmt : off _SCREAMING_SNAKE_CASE : Any = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing _SCREAMING_SNAKE_CASE : Union[str, Any] = re.compile( F"""[{''.join(map(__lowerCamelCase , list(range(0 , 9 ) ) + list(range(1_1 , 3_2 ) ) + list(range(1_2_7 , 1_6_0 ) ) + [1_6_0, 1_7_3, 8_2_0_3] ) )}]""" ) def __getstate__( self ) -> str: _SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Tuple = None return state def __setstate__( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : List[str] = {} _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self ) -> int: return len(self.sp_model ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : str = self.non_printing_characters_re.sub("" , __lowerCamelCase ) # Normalize whitespaces _SCREAMING_SNAKE_CASE : List[Any] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization _SCREAMING_SNAKE_CASE : Tuple = unicodedata.normalize("NFC" , __lowerCamelCase ) return text def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[Any] = self.preprocess_text(__lowerCamelCase ) return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> int: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) @staticmethod def UpperCamelCase_ ( __lowerCamelCase ) -> str: return out_string def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = [] _SCREAMING_SNAKE_CASE : Any = "" _SCREAMING_SNAKE_CASE : Optional[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string def UpperCamelCase_ ( self ) -> Dict[str, int]: _SCREAMING_SNAKE_CASE : List[Any] = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : Dict = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : str = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.encode(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE : Any = [self.preprocess_text(__lowerCamelCase ) for t in text] _SCREAMING_SNAKE_CASE : int = self.sp_model.encode(__lowerCamelCase ) if return_tensors is True or return_tensors == "pt": _SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(__lowerCamelCase ) return token_ids def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.decode(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[int]: _SCREAMING_SNAKE_CASE : Any = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] _SCREAMING_SNAKE_CASE : List[str] = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(__lowerCamelCase ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=__lowerCamelCase )
325
from math import isqrt, loga def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 800800, __lowerCamelCase = 800800 ): _SCREAMING_SNAKE_CASE : Optional[int] = degree * loga(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = calculate_prime_numbers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
325
1
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } UpperCamelCase__ =[ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): for attribute in key.split("." ): _SCREAMING_SNAKE_CASE : List[str] = getattr(__lowerCamelCase, __lowerCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE : str = getattr(__lowerCamelCase, __lowerCamelCase ).shape else: _SCREAMING_SNAKE_CASE : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _SCREAMING_SNAKE_CASE : Optional[Any] = value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "bias": _SCREAMING_SNAKE_CASE : Dict = value else: _SCREAMING_SNAKE_CASE : List[Any] = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [] _SCREAMING_SNAKE_CASE : List[Any] = fairseq_model.state_dict() _SCREAMING_SNAKE_CASE : Optional[int] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _SCREAMING_SNAKE_CASE : List[str] = None for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE : Any = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, hf_model.config.feat_extract_norm == "group", ) _SCREAMING_SNAKE_CASE : Optional[Any] = True elif name.split("." )[0] == "proj": _SCREAMING_SNAKE_CASE : Optional[int] = fairseq_model.proj _SCREAMING_SNAKE_CASE : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: _SCREAMING_SNAKE_CASE : List[Any] = True if "*" in mapped_key: _SCREAMING_SNAKE_CASE : int = name.split(__lowerCamelCase )[0].split("." )[-2] _SCREAMING_SNAKE_CASE : str = mapped_key.replace("*", __lowerCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE : List[Any] = "weight_g" elif "weight_v" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = "weight_v" elif "bias" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = "bias" elif "weight" in name: _SCREAMING_SNAKE_CASE : Union[str, Any] = "weight" else: _SCREAMING_SNAKE_CASE : List[Any] = None set_recursively(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = full_name.split("conv_layers." )[-1] _SCREAMING_SNAKE_CASE : Optional[int] = name.split("." ) _SCREAMING_SNAKE_CASE : str = int(items[0] ) _SCREAMING_SNAKE_CASE : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _SCREAMING_SNAKE_CASE : str = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _SCREAMING_SNAKE_CASE : List[Any] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _SCREAMING_SNAKE_CASE : Optional[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _SCREAMING_SNAKE_CASE : List[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = emb.weight.shape _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase, __lowerCamelCase, bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = emb.weight.data return lin_layer def lowerCamelCase__ (__lowerCamelCase ): with open(__lowerCamelCase, "r", encoding="utf-8" ) as f: _SCREAMING_SNAKE_CASE : List[Any] = f.readlines() _SCREAMING_SNAKE_CASE : List[str] = [line.split(" " )[0] for line in lines] _SCREAMING_SNAKE_CASE : Optional[Any] = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(__lowerCamelCase, range(4, num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, ): _SCREAMING_SNAKE_CASE : List[Any] = WavaVecaConfig.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = SpeechaTextaConfig.from_pretrained( __lowerCamelCase, vocab_size=__lowerCamelCase, decoder_layers=__lowerCamelCase, do_stable_layer_norm=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=16000, padding_value=0, do_normalize=__lowerCamelCase, return_attention_mask=__lowerCamelCase, ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) _SCREAMING_SNAKE_CASE : str = model[0].eval() # set weights for wav2vec2 encoder _SCREAMING_SNAKE_CASE : Dict = WavaVecaModel(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = recursively_load_weights_wavaveca(model.encoder, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = SpeechaTextaForCausalLM(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=__lowerCamelCase ) # set output linear layer unexpected_keys.remove("embed_out" ) _SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _SCREAMING_SNAKE_CASE : Dict = SpeechEncoderDecoderModel(encoder=__lowerCamelCase, decoder=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = False # add projection layer _SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(projection_layer.weight ) _SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(projection_layer.bias ) _SCREAMING_SNAKE_CASE : List[Any] = create_vocab_dict(__lowerCamelCase ) with open(os.path.join(__lowerCamelCase, "vocab.json" ), "w" ) as fp: json.dump(__lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = SpeechaTextaTokenizer(os.path.join(__lowerCamelCase, "vocab.json" ) ) tokenizer.save_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = hf_wavavec.config.to_dict() _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.pad_token_id _SCREAMING_SNAKE_CASE : str = tokenizer.bos_token_id _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.eos_token_id _SCREAMING_SNAKE_CASE : List[str] = "speech_to_text_2" _SCREAMING_SNAKE_CASE : Tuple = "wav2vec2" _SCREAMING_SNAKE_CASE : List[Any] = SpeechEncoderDecoderConfig.from_dict(__lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) feature_extractor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_0224, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') UpperCamelCase__ =parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
325
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(__lowerCamelCase ) // (factorial(__lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( 'The number of five-card hands possible from a standard', f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( 'If a class of 40 students must be arranged into groups of', f"4 for group projects, there are {combinations(40, 4)} ways", 'to arrange them.\n', ) print( 'If 10 teams are competing in a Formula One race, there', f"are {combinations(10, 3)} ways that first, second and", 'third place can be awarded.', )
325
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'decision_transformer' __snake_case = ['past_key_values'] __snake_case = { 'max_position_embeddings': 'n_positions', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , __lowerCamelCase=1_7 , __lowerCamelCase=4 , __lowerCamelCase=1_2_8 , __lowerCamelCase=4_0_9_6 , __lowerCamelCase=True , __lowerCamelCase=1 , __lowerCamelCase=1_0_2_4 , __lowerCamelCase=3 , __lowerCamelCase=1 , __lowerCamelCase=None , __lowerCamelCase="relu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=1E-5 , __lowerCamelCase=0.02 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=5_0_2_5_6 , __lowerCamelCase=5_0_2_5_6 , __lowerCamelCase=False , __lowerCamelCase=False , **__lowerCamelCase , ) -> int: _SCREAMING_SNAKE_CASE : Optional[Any] = state_dim _SCREAMING_SNAKE_CASE : List[Any] = act_dim _SCREAMING_SNAKE_CASE : Any = hidden_size _SCREAMING_SNAKE_CASE : List[Any] = max_ep_len _SCREAMING_SNAKE_CASE : Any = action_tanh _SCREAMING_SNAKE_CASE : Any = vocab_size _SCREAMING_SNAKE_CASE : Any = n_positions _SCREAMING_SNAKE_CASE : Optional[int] = n_layer _SCREAMING_SNAKE_CASE : List[Any] = n_head _SCREAMING_SNAKE_CASE : Dict = n_inner _SCREAMING_SNAKE_CASE : str = activation_function _SCREAMING_SNAKE_CASE : Tuple = resid_pdrop _SCREAMING_SNAKE_CASE : Union[str, Any] = embd_pdrop _SCREAMING_SNAKE_CASE : Dict = attn_pdrop _SCREAMING_SNAKE_CASE : List[Any] = layer_norm_epsilon _SCREAMING_SNAKE_CASE : List[str] = initializer_range _SCREAMING_SNAKE_CASE : Any = scale_attn_weights _SCREAMING_SNAKE_CASE : Tuple = use_cache _SCREAMING_SNAKE_CASE : Tuple = scale_attn_by_inverse_layer_idx _SCREAMING_SNAKE_CASE : str = reorder_and_upcast_attn _SCREAMING_SNAKE_CASE : int = bos_token_id _SCREAMING_SNAKE_CASE : str = eos_token_id super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 1_2_8 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 2000.0 , __lowerCamelCase = 7_6_8 , __lowerCamelCase = 1_2 , __lowerCamelCase = 1_2 , __lowerCamelCase = 6_4 , __lowerCamelCase = 2_0_4_8 , __lowerCamelCase = 0.1 , ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential( nn.Linear(__lowerCamelCase , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__lowerCamelCase ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : str = nn.Embedding(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() for lyr_num in range(__lowerCamelCase ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Optional[int] = DecoderLayer(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) self.decoders.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(__lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : Optional[int] = torch.broadcast_to( torch.arange(__lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.position_encoding(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.continuous_inputs_projection(__lowerCamelCase ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Any = self.dropout(__lowerCamelCase ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Any = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : List[str] = [(x, self.encoder_decoder_mask(__lowerCamelCase , __lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : Tuple = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Optional[Any] = lyr( __lowerCamelCase , conditioning_emb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , )[0] _SCREAMING_SNAKE_CASE : int = self.decoder_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = self.spec_out(__lowerCamelCase ) return spec_out class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__lowerCamelCase , d_kv=__lowerCamelCase , num_heads=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.layer[0]( __lowerCamelCase , conditioning_emb=__lowerCamelCase , attention_mask=__lowerCamelCase , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : str = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : Tuple = self.layer[1]( __lowerCamelCase , key_value_states=__lowerCamelCase , attention_mask=__lowerCamelCase , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Optional[Any] = self.layer[-1](__lowerCamelCase , __lowerCamelCase ) return (hidden_states,) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> Union[str, Any]: # pre_self_attention_layer_norm _SCREAMING_SNAKE_CASE : int = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Any = self.FiLMLayer(__lowerCamelCase , __lowerCamelCase ) # Self-attention block _SCREAMING_SNAKE_CASE : Optional[int] = self.attention(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = Attention(query_dim=__lowerCamelCase , heads=__lowerCamelCase , dim_head=__lowerCamelCase , out_bias=__lowerCamelCase , scale_qk=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.attention( __lowerCamelCase , encoder_hidden_states=__lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.dropout(__lowerCamelCase ) return layer_output class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=__lowerCamelCase , d_ff=__lowerCamelCase , dropout_rate=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(__lowerCamelCase , eps=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=None ) -> List[str]: _SCREAMING_SNAKE_CASE : Optional[int] = self.layer_norm(__lowerCamelCase ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.film(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.DenseReluDense(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = NewGELUActivation() def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: _SCREAMING_SNAKE_CASE : Dict = self.act(self.wi_a(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Dict = self.wi_a(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Optional[int] = self.dropout(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = self.wo(__lowerCamelCase ) return hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1E-6 ) -> int: super().__init__() _SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.ones(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : str = eps def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : str = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowerCAmelCase__( nn.Module ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> torch.Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(__lowerCamelCase , 3.0 )) )) class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__() _SCREAMING_SNAKE_CASE : Any = nn.Linear(__lowerCamelCase , out_features * 2 , bias=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.scale_bias(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = torch.chunk(__lowerCamelCase , 2 , -1 ) _SCREAMING_SNAKE_CASE : Optional[int] = x * (1 + scale) + shift return x
325
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ =OrderedDict( [ ('align', 'EfficientNetImageProcessor'), ('beit', 'BeitImageProcessor'), ('bit', 'BitImageProcessor'), ('blip', 'BlipImageProcessor'), ('blip-2', 'BlipImageProcessor'), ('bridgetower', 'BridgeTowerImageProcessor'), ('chinese_clip', 'ChineseCLIPImageProcessor'), ('clip', 'CLIPImageProcessor'), ('clipseg', 'ViTImageProcessor'), ('conditional_detr', 'ConditionalDetrImageProcessor'), ('convnext', 'ConvNextImageProcessor'), ('convnextv2', 'ConvNextImageProcessor'), ('cvt', 'ConvNextImageProcessor'), ('data2vec-vision', 'BeitImageProcessor'), ('deformable_detr', 'DeformableDetrImageProcessor'), ('deit', 'DeiTImageProcessor'), ('deta', 'DetaImageProcessor'), ('detr', 'DetrImageProcessor'), ('dinat', 'ViTImageProcessor'), ('donut-swin', 'DonutImageProcessor'), ('dpt', 'DPTImageProcessor'), ('efficientformer', 'EfficientFormerImageProcessor'), ('efficientnet', 'EfficientNetImageProcessor'), ('flava', 'FlavaImageProcessor'), ('focalnet', 'BitImageProcessor'), ('git', 'CLIPImageProcessor'), ('glpn', 'GLPNImageProcessor'), ('groupvit', 'CLIPImageProcessor'), ('imagegpt', 'ImageGPTImageProcessor'), ('instructblip', 'BlipImageProcessor'), ('layoutlmv2', 'LayoutLMv2ImageProcessor'), ('layoutlmv3', 'LayoutLMv3ImageProcessor'), ('levit', 'LevitImageProcessor'), ('mask2former', 'Mask2FormerImageProcessor'), ('maskformer', 'MaskFormerImageProcessor'), ('mgp-str', 'ViTImageProcessor'), ('mobilenet_v1', 'MobileNetV1ImageProcessor'), ('mobilenet_v2', 'MobileNetV2ImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevitv2', 'MobileViTImageProcessor'), ('nat', 'ViTImageProcessor'), ('oneformer', 'OneFormerImageProcessor'), ('owlvit', 'OwlViTImageProcessor'), ('perceiver', 'PerceiverImageProcessor'), ('pix2struct', 'Pix2StructImageProcessor'), ('poolformer', 'PoolFormerImageProcessor'), ('regnet', 'ConvNextImageProcessor'), ('resnet', 'ConvNextImageProcessor'), ('sam', 'SamImageProcessor'), ('segformer', 'SegformerImageProcessor'), ('swiftformer', 'ViTImageProcessor'), ('swin', 'ViTImageProcessor'), ('swin2sr', 'Swin2SRImageProcessor'), ('swinv2', 'ViTImageProcessor'), ('table-transformer', 'DetrImageProcessor'), ('timesformer', 'VideoMAEImageProcessor'), ('tvlt', 'TvltImageProcessor'), ('upernet', 'SegformerImageProcessor'), ('van', 'ConvNextImageProcessor'), ('videomae', 'VideoMAEImageProcessor'), ('vilt', 'ViltImageProcessor'), ('vit', 'ViTImageProcessor'), ('vit_hybrid', 'ViTHybridImageProcessor'), ('vit_mae', 'ViTImageProcessor'), ('vit_msn', 'ViTImageProcessor'), ('xclip', 'CLIPImageProcessor'), ('yolos', 'YolosImageProcessor'), ] ) UpperCamelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def lowerCamelCase__ (__lowerCamelCase ): for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: _SCREAMING_SNAKE_CASE : str = model_type_to_module_name(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = importlib.import_module(f""".{module_name}""", "transformers.models" ) try: return getattr(__lowerCamelCase, __lowerCamelCase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(__lowerCamelCase, "__name__", __lowerCamelCase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _SCREAMING_SNAKE_CASE : str = importlib.import_module("transformers" ) if hasattr(__lowerCamelCase, __lowerCamelCase ): return getattr(__lowerCamelCase, __lowerCamelCase ) return None def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase = None, __lowerCamelCase = False, __lowerCamelCase = False, __lowerCamelCase = None, __lowerCamelCase = None, __lowerCamelCase = None, __lowerCamelCase = False, **__lowerCamelCase, ): _SCREAMING_SNAKE_CASE : List[str] = get_file_from_repo( __lowerCamelCase, __lowerCamelCase, cache_dir=__lowerCamelCase, force_download=__lowerCamelCase, resume_download=__lowerCamelCase, proxies=__lowerCamelCase, use_auth_token=__lowerCamelCase, revision=__lowerCamelCase, local_files_only=__lowerCamelCase, ) if resolved_config_file is None: logger.info( "Could not locate the image processor configuration file, will try to use the model config instead." ) return {} with open(__lowerCamelCase, encoding="utf-8" ) as reader: return json.load(__lowerCamelCase ) class lowerCAmelCase__: '''simple docstring''' def __init__( self ) -> int: raise EnvironmentError( "AutoImageProcessor is designed to be instantiated " "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(__lowerCamelCase ) def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.pop("config" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = kwargs.pop("trust_remote_code" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = True _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = ImageProcessingMixin.get_image_processor_dict(__lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = config_dict.get("image_processor_type" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = None if "AutoImageProcessor" in config_dict.get("auto_map" , {} ): _SCREAMING_SNAKE_CASE : Optional[Any] = config_dict["auto_map"]["AutoImageProcessor"] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: _SCREAMING_SNAKE_CASE : Any = config_dict.pop("feature_extractor_type" , __lowerCamelCase ) if feature_extractor_class is not None: logger.warning( "Could not find image processor class in the image processor config or the model config. Loading" " based on pattern matching with the model's feature extractor configuration." ) _SCREAMING_SNAKE_CASE : List[Any] = feature_extractor_class.replace("FeatureExtractor" , "ImageProcessor" ) if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): _SCREAMING_SNAKE_CASE : str = config_dict["auto_map"]["AutoFeatureExtractor"] _SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor_auto_map.replace("FeatureExtractor" , "ImageProcessor" ) logger.warning( "Could not find image processor auto map in the image processor config or the model config." " Loading based on pattern matching with the model's feature extractor configuration." ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) # It could be in `config.image_processor_type`` _SCREAMING_SNAKE_CASE : Any = getattr(__lowerCamelCase , "image_processor_type" , __lowerCamelCase ) if hasattr(__lowerCamelCase , "auto_map" ) and "AutoImageProcessor" in config.auto_map: _SCREAMING_SNAKE_CASE : List[Any] = config.auto_map["AutoImageProcessor"] if image_processor_class is not None: _SCREAMING_SNAKE_CASE : Any = image_processor_class_from_name(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = image_processor_auto_map is not None _SCREAMING_SNAKE_CASE : List[Any] = image_processor_class is not None or type(__lowerCamelCase ) in IMAGE_PROCESSOR_MAPPING _SCREAMING_SNAKE_CASE : List[Any] = resolve_trust_remote_code( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if has_remote_code and trust_remote_code: _SCREAMING_SNAKE_CASE : Dict = get_class_from_dynamic_module( __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = kwargs.pop("code_revision" , __lowerCamelCase ) if os.path.isdir(__lowerCamelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__lowerCamelCase , **__lowerCamelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(__lowerCamelCase , **__lowerCamelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__lowerCamelCase ) in IMAGE_PROCESSOR_MAPPING: _SCREAMING_SNAKE_CASE : Dict = IMAGE_PROCESSOR_MAPPING[type(__lowerCamelCase )] return image_processor_class.from_dict(__lowerCamelCase , **__lowerCamelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: IMAGE_PROCESSOR_MAPPING.register(__lowerCamelCase , __lowerCamelCase )
325
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 for i in range(1, n + 1 ): # to compute current row from previous row. _SCREAMING_SNAKE_CASE : Union[str, Any] = min(__lowerCamelCase, __lowerCamelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=__lowercase ) class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = field(default='summarization' , metadata={'include_in_asdict_even_if_is_default': True} ) __snake_case = Features({'text': Value('string' )} ) __snake_case = Features({'summary': Value('string' )} ) __snake_case = "text" __snake_case = "summary" @property def UpperCamelCase_ ( self ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={ 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = 'timesformer' def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> List[str]: super().__init__(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : str = patch_size _SCREAMING_SNAKE_CASE : str = num_channels _SCREAMING_SNAKE_CASE : str = num_frames _SCREAMING_SNAKE_CASE : Dict = hidden_size _SCREAMING_SNAKE_CASE : Any = num_hidden_layers _SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads _SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size _SCREAMING_SNAKE_CASE : Optional[int] = hidden_act _SCREAMING_SNAKE_CASE : int = hidden_dropout_prob _SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps _SCREAMING_SNAKE_CASE : List[str] = qkv_bias _SCREAMING_SNAKE_CASE : Tuple = attention_type _SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate
325
1
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=5 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_0 , __lowerCamelCase=0.02 , __lowerCamelCase=True , __lowerCamelCase=None , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Dict = parent _SCREAMING_SNAKE_CASE : str = batch_size _SCREAMING_SNAKE_CASE : List[str] = seq_length _SCREAMING_SNAKE_CASE : List[str] = is_training _SCREAMING_SNAKE_CASE : Tuple = use_input_mask _SCREAMING_SNAKE_CASE : str = vocab_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size _SCREAMING_SNAKE_CASE : str = num_hidden_layers _SCREAMING_SNAKE_CASE : Any = num_attention_heads _SCREAMING_SNAKE_CASE : List[Any] = intermediate_size _SCREAMING_SNAKE_CASE : List[str] = hidden_act _SCREAMING_SNAKE_CASE : str = hidden_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : Dict = max_position_embeddings _SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range _SCREAMING_SNAKE_CASE : int = use_labels _SCREAMING_SNAKE_CASE : List[str] = scope def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self ) -> Optional[Any]: return BertGenerationConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self ) -> Tuple: ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : Dict = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase , ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = BertGenerationEncoder(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase , ) -> List[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = True _SCREAMING_SNAKE_CASE : Tuple = BertGenerationEncoder(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : List[str] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : int = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase , ) -> Any: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : List[str] = BertGenerationDecoder(config=__lowerCamelCase ).to(__lowerCamelCase ).eval() # first forward pass _SCREAMING_SNAKE_CASE : str = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Optional[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _SCREAMING_SNAKE_CASE : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE : int = torch.cat([input_mask, next_mask] , dim=-1 ) _SCREAMING_SNAKE_CASE : Tuple = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["hidden_states"][0] _SCREAMING_SNAKE_CASE : List[Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["hidden_states"][0] # select random slice _SCREAMING_SNAKE_CASE : str = ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx].detach() _SCREAMING_SNAKE_CASE : List[str] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , *__lowerCamelCase , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = BertGenerationDecoder(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE : Optional[Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE : List[str] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__( __lowercase , __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __snake_case = (BertGenerationDecoder,) if is_torch_available() else () __snake_case = ( {'feature-extraction': BertGenerationEncoder, 'text-generation': BertGenerationDecoder} if is_torch_available() else {} ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : Dict = BertGenerationEncoderTester(self ) _SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert" self.model_tester.create_and_check_model(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self ) -> Any: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: # This regression test was failing with PyTorch < 1.3 ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : Any = self.model_tester.prepare_config_and_inputs_for_decoder() _SCREAMING_SNAKE_CASE : Tuple = None self.model_tester.create_and_check_model_as_decoder( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(__lowerCamelCase ) @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) _SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size([1, 8, 1_0_2_4] ) self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) ) @require_torch class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[Any] = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = torch.Size([1, 8, 5_0_3_5_8] ) self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ={'vocab_file': 'spiece.model'} UpperCamelCase__ ={ 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } UpperCamelCase__ ={ 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } UpperCamelCase__ ='▁' class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __lowerCamelCase , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase="[CLS]" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<unk>" , __lowerCamelCase="[SEP]" , __lowerCamelCase="<pad>" , __lowerCamelCase="[CLS]" , __lowerCamelCase="[MASK]" , __lowerCamelCase = None , **__lowerCamelCase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _SCREAMING_SNAKE_CASE : List[Any] = ( AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase , normalized=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token ) _SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = do_lower_case _SCREAMING_SNAKE_CASE : List[Any] = remove_space _SCREAMING_SNAKE_CASE : str = keep_accents _SCREAMING_SNAKE_CASE : Optional[int] = vocab_file _SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase_ ( self ) -> Optional[Any]: return len(self.sp_model ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : str = self.__dict__.copy() _SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self , __lowerCamelCase ) -> Tuple: _SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _SCREAMING_SNAKE_CASE : Optional[int] = {} _SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[int]: if self.remove_space: _SCREAMING_SNAKE_CASE : List[str] = " ".join(inputs.strip().split() ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = inputs _SCREAMING_SNAKE_CASE : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: _SCREAMING_SNAKE_CASE : str = unicodedata.normalize("NFKD" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = "".join([c for c in outputs if not unicodedata.combining(__lowerCamelCase )] ) if self.do_lower_case: _SCREAMING_SNAKE_CASE : Dict = outputs.lower() return outputs def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[str]: _SCREAMING_SNAKE_CASE : int = self.preprocess_text(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for piece in pieces: if len(__lowerCamelCase ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): _SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCamelCase , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[1:] else: _SCREAMING_SNAKE_CASE : Tuple = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCamelCase ) else: new_pieces.append(__lowerCamelCase ) return new_pieces def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> str: return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Dict: _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : List[str] = "" _SCREAMING_SNAKE_CASE : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowerCamelCase ) + token _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] _SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> List[int]: _SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] _SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None ) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _SCREAMING_SNAKE_CASE : List[Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCamelCase , "wb" ) as fi: _SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
325
1
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected", [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(__lowerCamelCase, i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0, 4 ), range(4, 7 ), range(7, 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0, 1 ), range(1, 2 ), range(2, 3 )]), ], ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : int = _distribute_shards(**__lowerCamelCase ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected", [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ], ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = _split_gen_kwargs(__lowerCamelCase, __lowerCamelCase ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected", [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ], ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if expected is RuntimeError: with pytest.raises(__lowerCamelCase ): _number_of_shards_in_gen_kwargs(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE : Dict = _number_of_shards_in_gen_kwargs(__lowerCamelCase ) assert out == expected
325
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ =logging.get_logger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , *__lowerCamelCase , **__lowerCamelCase ) -> None: warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
325
1
import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase="shi-labs/oneformer_demo" ): with open(hf_hub_download(__lowerCamelCase, __lowerCamelCase, repo_type="dataset" ), "r" ) as f: _SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = {} _SCREAMING_SNAKE_CASE : str = [] _SCREAMING_SNAKE_CASE : int = [] for key, info in class_info.items(): _SCREAMING_SNAKE_CASE : Dict = info["name"] class_names.append(info["name"] ) if info["isthing"]: thing_ids.append(int(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Optional[int] = thing_ids _SCREAMING_SNAKE_CASE : Tuple = class_names return metadata class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=7 , __lowerCamelCase=3 , __lowerCamelCase=3_0 , __lowerCamelCase=4_0_0 , __lowerCamelCase=None , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=[0.5, 0.5, 0.5] , __lowerCamelCase=[0.5, 0.5, 0.5] , __lowerCamelCase=1_0 , __lowerCamelCase=False , __lowerCamelCase=2_5_5 , __lowerCamelCase="shi-labs/oneformer_demo" , __lowerCamelCase="ade20k_panoptic.json" , __lowerCamelCase=1_0 , ) -> List[str]: _SCREAMING_SNAKE_CASE : int = parent _SCREAMING_SNAKE_CASE : Optional[Any] = batch_size _SCREAMING_SNAKE_CASE : int = num_channels _SCREAMING_SNAKE_CASE : Dict = min_resolution _SCREAMING_SNAKE_CASE : Any = max_resolution _SCREAMING_SNAKE_CASE : Any = do_resize _SCREAMING_SNAKE_CASE : Any = {"shortest_edge": 3_2, "longest_edge": 1_3_3_3} if size is None else size _SCREAMING_SNAKE_CASE : Optional[int] = do_normalize _SCREAMING_SNAKE_CASE : List[str] = image_mean _SCREAMING_SNAKE_CASE : Any = image_std _SCREAMING_SNAKE_CASE : Optional[Any] = class_info_file _SCREAMING_SNAKE_CASE : Optional[int] = prepare_metadata(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = num_text _SCREAMING_SNAKE_CASE : Tuple = repo_path # for the post_process_functions _SCREAMING_SNAKE_CASE : List[str] = 2 _SCREAMING_SNAKE_CASE : List[Any] = 1_0 _SCREAMING_SNAKE_CASE : Optional[int] = 1_0 _SCREAMING_SNAKE_CASE : Optional[int] = 3 _SCREAMING_SNAKE_CASE : Tuple = 4 _SCREAMING_SNAKE_CASE : str = num_labels _SCREAMING_SNAKE_CASE : Dict = do_reduce_labels _SCREAMING_SNAKE_CASE : str = ignore_index def UpperCamelCase_ ( self ) -> Optional[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase=False ) -> List[Any]: if not batched: _SCREAMING_SNAKE_CASE : List[str] = image_inputs[0] if isinstance(__lowerCamelCase , Image.Image ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = image.size else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = image.shape[1], image.shape[2] if w < h: _SCREAMING_SNAKE_CASE : List[str] = int(self.size["shortest_edge"] * h / w ) _SCREAMING_SNAKE_CASE : Tuple = self.size["shortest_edge"] elif w > h: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.size["shortest_edge"] _SCREAMING_SNAKE_CASE : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: _SCREAMING_SNAKE_CASE : List[str] = self.size["shortest_edge"] _SCREAMING_SNAKE_CASE : Dict = self.size["shortest_edge"] else: _SCREAMING_SNAKE_CASE : Dict = [] for image in image_inputs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[0] )[0] _SCREAMING_SNAKE_CASE : List[str] = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[1] )[1] return expected_height, expected_width def UpperCamelCase_ ( self ) -> Union[str, Any]: return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class lowerCAmelCase__( __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __snake_case = image_processing_class def UpperCamelCase_ ( self ) -> List[str]: _SCREAMING_SNAKE_CASE : Any = OneFormerImageProcessorTester(self ) @property def UpperCamelCase_ ( self ) -> int: return self.image_processing_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(__lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "size" ) ) self.assertTrue(hasattr(__lowerCamelCase , "ignore_index" ) ) self.assertTrue(hasattr(__lowerCamelCase , "class_info_file" ) ) self.assertTrue(hasattr(__lowerCamelCase , "num_text" ) ) self.assertTrue(hasattr(__lowerCamelCase , "repo_path" ) ) self.assertTrue(hasattr(__lowerCamelCase , "metadata" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_reduce_labels" ) ) def UpperCamelCase_ ( self ) -> List[Any]: pass def UpperCamelCase_ ( self ) -> List[str]: # Initialize image_processor _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE : Any = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self.image_processing_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = self.image_processing_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = image_processor( __lowerCamelCase , ["semantic"] * len(__lowerCamelCase ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> Dict: # Initialize image_processor _SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE : Tuple = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input _SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.image_processing_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.image_processing_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = image_processor( __lowerCamelCase , ["semantic"] * len(__lowerCamelCase ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> str: # Initialize image_processor _SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE : Any = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = self.image_processing_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.image_processing_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = image_processor( __lowerCamelCase , ["semantic"] * len(__lowerCamelCase ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase="np" ) -> Tuple: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target _SCREAMING_SNAKE_CASE : str = self.image_processing_tester.num_labels _SCREAMING_SNAKE_CASE : Dict = None _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCamelCase ) if with_segmentation_maps: _SCREAMING_SNAKE_CASE : List[Any] = num_labels if is_instance_map: _SCREAMING_SNAKE_CASE : str = list(range(__lowerCamelCase ) ) * 2 _SCREAMING_SNAKE_CASE : int = dict(enumerate(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": _SCREAMING_SNAKE_CASE : Optional[int] = [Image.fromarray(__lowerCamelCase ) for annotation in annotations] _SCREAMING_SNAKE_CASE : List[Any] = image_processor( __lowerCamelCase , ["semantic"] * len(__lowerCamelCase ) , __lowerCamelCase , return_tensors="pt" , instance_id_to_semantic_id=__lowerCamelCase , pad_and_return_pixel_mask=__lowerCamelCase , ) return inputs def UpperCamelCase_ ( self ) -> Optional[Any]: pass def UpperCamelCase_ ( self ) -> Dict: def common(__lowerCamelCase=False , __lowerCamelCase=None ): _SCREAMING_SNAKE_CASE : Any = self.comm_get_image_processor_inputs( with_segmentation_maps=__lowerCamelCase , is_instance_map=__lowerCamelCase , segmentation_type=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = inputs["mask_labels"] _SCREAMING_SNAKE_CASE : Any = inputs["class_labels"] _SCREAMING_SNAKE_CASE : List[Any] = inputs["pixel_values"] _SCREAMING_SNAKE_CASE : Optional[int] = inputs["text_inputs"] # check the batch_size for mask_label, class_label, text_input in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(__lowerCamelCase ) , self.image_processing_tester.num_text ) common() common(is_instance_map=__lowerCamelCase ) common(is_instance_map=__lowerCamelCase , segmentation_type="pil" ) common(is_instance_map=__lowerCamelCase , segmentation_type="pil" ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = np.zeros((2_0, 5_0) ) _SCREAMING_SNAKE_CASE : int = 1 _SCREAMING_SNAKE_CASE : int = 1 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : Optional[int] = binary_mask_to_rle(__lowerCamelCase ) self.assertEqual(len(__lowerCamelCase ) , 4 ) self.assertEqual(rle[0] , 2_1 ) self.assertEqual(rle[1] , 4_5 ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs() _SCREAMING_SNAKE_CASE : Optional[int] = fature_extractor.post_process_semantic_segmentation(__lowerCamelCase ) self.assertEqual(len(__lowerCamelCase ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) _SCREAMING_SNAKE_CASE : List[Any] = [(1, 4) for i in range(self.image_processing_tester.batch_size )] _SCREAMING_SNAKE_CASE : str = fature_extractor.post_process_semantic_segmentation(__lowerCamelCase , target_sizes=__lowerCamelCase ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs() _SCREAMING_SNAKE_CASE : List[Any] = image_processor.post_process_instance_segmentation(__lowerCamelCase , threshold=0 ) self.assertTrue(len(__lowerCamelCase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) , __lowerCamelCase ) self.assertEqual( el["segmentation"].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : int = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _SCREAMING_SNAKE_CASE : str = self.image_processing_tester.get_fake_oneformer_outputs() _SCREAMING_SNAKE_CASE : Any = image_processor.post_process_panoptic_segmentation(__lowerCamelCase , threshold=0 ) self.assertTrue(len(__lowerCamelCase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) , __lowerCamelCase ) self.assertEqual( el["segmentation"].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
325
import numpy as np import datasets UpperCamelCase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' UpperCamelCase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' UpperCamelCase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence" ) , id="X" ), } ) , ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: # convert to numpy arrays _SCREAMING_SNAKE_CASE : Dict = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = np.array(__lowerCamelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError("Expected `X` to be a 2D vector" ) if len(reference_distribution.shape ) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector" ) if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension" ) # Get mahalanobis distance for each prediction _SCREAMING_SNAKE_CASE : Any = X - np.mean(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.cov(reference_distribution.T ) try: _SCREAMING_SNAKE_CASE : Optional[int] = np.linalg.inv(__lowerCamelCase ) except np.linalg.LinAlgError: _SCREAMING_SNAKE_CASE : List[str] = np.linalg.pinv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = np.dot(__lowerCamelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 10**-10 ): _SCREAMING_SNAKE_CASE : int = a while True: _SCREAMING_SNAKE_CASE : int = Decimal(__lowerCamelCase ) - ( Decimal(eval(__lowerCamelCase ) ) / Decimal(eval(str(diff(__lowerCamelCase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__lowerCamelCase ) ) < precision: # noqa: S307 return float(__lowerCamelCase ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
325
from __future__ import annotations import math def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(__lowerCamelCase ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) return min( minimax(depth + 1, node_index * 2, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), minimax(depth + 1, node_index * 2 + 1, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ), ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = [90, 23, 6, 33, 21, 65, 123, 34423] _SCREAMING_SNAKE_CASE : Tuple = math.log(len(__lowerCamelCase ), 2 ) print("Optimal value : ", end="" ) print(minimax(0, 0, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
325
1
from math import pi def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/diffusers' UpperCamelCase__ ='.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase__ =importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase__ =spec.loader.load_module() def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$", __lowerCamelCase ) is not None def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = object_name.split("." ) _SCREAMING_SNAKE_CASE : List[Any] = 0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase, f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase, parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase, f"""{module}.py""" ), "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE : Union[str, Any] = "" _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""", lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _SCREAMING_SNAKE_CASE : Optional[int] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index], __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : Optional[int] = lines[start_index:line_index] return "".join(__lowerCamelCase ) UpperCamelCase__ =re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase__ =re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase__ =re.compile(R'<FILL\s+[^>]*>') def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = code.split("\n" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"^(\s*)\S", lines[idx] ).groups()[0] return "" def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE : Union[str, Any] = f"""class Bla:\n{code}""" _SCREAMING_SNAKE_CASE : Any = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = black.format_str(__lowerCamelCase, mode=__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = style_docstrings_in_code(__lowerCamelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=False ): with open(__lowerCamelCase, "r", encoding="utf-8", newline="\n" ) as f: _SCREAMING_SNAKE_CASE : int = f.readlines() _SCREAMING_SNAKE_CASE : Dict = [] _SCREAMING_SNAKE_CASE : Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = search.groups() _SCREAMING_SNAKE_CASE : Any = find_code_in_diffusers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE : int = theoretical_indent _SCREAMING_SNAKE_CASE : str = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE : Any = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break _SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] _SCREAMING_SNAKE_CASE : str = _should_continue(__lowerCamelCase, __lowerCamelCase ) and re.search(f"""^{indent}# End copy""", __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _SCREAMING_SNAKE_CASE : List[Any] = lines[start_index:line_index] _SCREAMING_SNAKE_CASE : Optional[Any] = "".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE : Dict = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(__lowerCamelCase ) is None] _SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : str = replace_pattern.replace("with", "" ).split("," ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = pattern.groups() _SCREAMING_SNAKE_CASE : Tuple = re.sub(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE : List[Any] = re.sub(obja.lower(), obja.lower(), __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = re.sub(obja.upper(), obja.upper(), __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _SCREAMING_SNAKE_CASE : int = blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE : List[str] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE : int = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase, "w", encoding="utf-8", newline="\n" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ (__lowerCamelCase = False ): _SCREAMING_SNAKE_CASE : int = glob.glob(os.path.join(__lowerCamelCase, "**/*.py" ), recursive=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [] for filename in all_files: _SCREAMING_SNAKE_CASE : int = is_copy_consistent(__lowerCamelCase, __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: _SCREAMING_SNAKE_CASE : Dict = "\n".join(__lowerCamelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase__ =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase__ =parser.parse_args() check_copies(args.fix_and_overwrite)
325
1
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class lowerCAmelCase__( __lowercase ): '''simple docstring''' def UpperCamelCase_ ( self , __lowerCamelCase ) -> List[Any]: with open(__lowerCamelCase , encoding="utf-8" ) as input_file: _SCREAMING_SNAKE_CASE : Tuple = re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) _SCREAMING_SNAKE_CASE : List[Any] = input_file.read() _SCREAMING_SNAKE_CASE : List[Any] = regexp.search(__lowerCamelCase ) return match def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: with open(__lowerCamelCase , encoding="utf-8" ) as input_file: _SCREAMING_SNAKE_CASE : Tuple = re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) _SCREAMING_SNAKE_CASE : Any = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` _SCREAMING_SNAKE_CASE : Union[str, Any] = regexp.finditer(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : List[Any] = Path("./datasets" ) _SCREAMING_SNAKE_CASE : int = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__lowerCamelCase ) ): raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""" ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Union[str, Any] = Path("./datasets" ) _SCREAMING_SNAKE_CASE : int = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(__lowerCamelCase ) ): raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""" )
325
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=1_3 , __lowerCamelCase=7 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=9_9 , __lowerCamelCase=3_2 , __lowerCamelCase=2 , __lowerCamelCase=4 , __lowerCamelCase=3_7 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=1_6 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=3 , __lowerCamelCase=4 , __lowerCamelCase=None , ) -> Any: _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = 1_3 _SCREAMING_SNAKE_CASE : List[str] = 7 _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : int = True _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : int = 9_9 _SCREAMING_SNAKE_CASE : str = 3_8_4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = 4 _SCREAMING_SNAKE_CASE : Dict = 3_7 _SCREAMING_SNAKE_CASE : Union[str, Any] = "gelu" _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : str = 0.1 _SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 _SCREAMING_SNAKE_CASE : Tuple = 1_6 _SCREAMING_SNAKE_CASE : Dict = 2 _SCREAMING_SNAKE_CASE : Any = 0.02 _SCREAMING_SNAKE_CASE : Any = 3 _SCREAMING_SNAKE_CASE : List[str] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 1_2_8 _SCREAMING_SNAKE_CASE : Optional[int] = 2 _SCREAMING_SNAKE_CASE : int = 9 _SCREAMING_SNAKE_CASE : List[str] = 1 _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE : List[Any] = None _SCREAMING_SNAKE_CASE : Union[str, Any] = None _SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _SCREAMING_SNAKE_CASE : str = [input_ids, input_mask] _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = TFConvBertForMaskedLM(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : int = self.num_labels _SCREAMING_SNAKE_CASE : str = TFConvBertForSequenceClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> str: _SCREAMING_SNAKE_CASE : Optional[int] = self.num_choices _SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForMultipleChoice(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(__lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE : List[Any] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: _SCREAMING_SNAKE_CASE : Dict = self.num_labels _SCREAMING_SNAKE_CASE : Tuple = TFConvBertForTokenClassification(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : Optional[int] = TFConvBertForQuestionAnswering(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _SCREAMING_SNAKE_CASE : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __snake_case = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : int = TFConvBertModelTester(self ) _SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def UpperCamelCase_ ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True if hasattr(__lowerCamelCase , "use_cache" ): _SCREAMING_SNAKE_CASE : List[str] = True _SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = len(model(__lowerCamelCase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = os.path.join(__lowerCamelCase , "saved_model" , "1" ) _SCREAMING_SNAKE_CASE : Optional[Any] = tf.keras.models.load_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = model(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : List[Any] = outputs["encoder_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs["encoder_attentions"] else: _SCREAMING_SNAKE_CASE : List[str] = outputs["hidden_states"] _SCREAMING_SNAKE_CASE : Dict = outputs["attentions"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase_ ( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) _SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , "key_length" , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , "key_length" , __lowerCamelCase ) def check_decoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCamelCase ) self.assertEqual(out_len % 2 , 0 ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) _SCREAMING_SNAKE_CASE : Any = len(__lowerCamelCase ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) if self.is_encoder_decoder: _SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_decoder_attentions_output(__lowerCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : List[Any] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) # Check attention is always last and order is fine _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Any = True _SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = model(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__lowerCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __lowerCamelCase ) check_encoder_attentions_output(__lowerCamelCase ) @require_tf class lowerCAmelCase__( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) _SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE : str = model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = [1, 6, 7_6_8] self.assertEqual(output.shape , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __lowerCamelCase , atol=1E-4 )
325
1
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=(), __lowerCamelCase=None, __lowerCamelCase="no", __lowerCamelCase="29500" ): _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : str = False if any(key.startswith("KAGGLE" ) for key in os.environ.keys() ): _SCREAMING_SNAKE_CASE : Any = True elif "IPython" in sys.modules: _SCREAMING_SNAKE_CASE : Any = "google.colab" in str(sys.modules["IPython"].get_ipython() ) try: _SCREAMING_SNAKE_CASE : Optional[int] = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f"""Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.""" ) if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME", __lowerCamelCase ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside " "your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if num_processes is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = 8 _SCREAMING_SNAKE_CASE : Optional[Any] = PrepareForLaunch(__lowerCamelCase, distributed_type="TPU" ) print(f"""Launching a training on {num_processes} TPU cores.""" ) xmp.spawn(__lowerCamelCase, args=__lowerCamelCase, nprocs=__lowerCamelCase, start_method="fork" ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on one CPU." ) function(*__lowerCamelCase ) else: if num_processes is None: raise ValueError( "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call." ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized " "inside your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if torch.cuda.is_initialized(): raise ValueError( "To launch a multi-GPU training from your notebook, you need to avoid running any instruction " "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA " "function." ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__lowerCamelCase, master_addr="127.0.01", master_port=__lowerCamelCase, mixed_precision=__lowerCamelCase ): _SCREAMING_SNAKE_CASE : int = PrepareForLaunch(__lowerCamelCase, distributed_type="MULTI_GPU" ) print(f"""Launching training on {num_processes} GPUs.""" ) try: start_processes(__lowerCamelCase, args=__lowerCamelCase, nprocs=__lowerCamelCase, start_method="fork" ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. " "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " "Please review your imports and test them when running the `notebook_launcher()` to identify " "which one is problematic." ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): _SCREAMING_SNAKE_CASE : int = "1" print("Launching training on MPS." ) elif torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on CPU." ) function(*__lowerCamelCase ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase=(), __lowerCamelCase=2 ): from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__lowerCamelCase, master_addr="127.0.01", master_port="29500", accelerate_mixed_precision="no", accelerate_debug_rdv_file=tmp_file.name, accelerate_use_cpu="yes", ): _SCREAMING_SNAKE_CASE : Optional[Any] = PrepareForLaunch(__lowerCamelCase, debug=__lowerCamelCase ) start_processes(__lowerCamelCase, args=__lowerCamelCase, nprocs=__lowerCamelCase, start_method="fork" )
325
from timeit import timeit def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ (__lowerCamelCase ): if number < 0: raise ValueError("the value of input must not be negative" ) _SCREAMING_SNAKE_CASE : str = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ (): def do_benchmark(__lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Tuple = "import __main__ as z" print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : str = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=__lowerCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__lowerCamelCase ) = }""" ) _SCREAMING_SNAKE_CASE : int = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=__lowerCamelCase, ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
325
1
from torch import nn class lowerCAmelCase__( nn.Module ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple: super().__init__() _SCREAMING_SNAKE_CASE : List[Any] = class_size _SCREAMING_SNAKE_CASE : int = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) _SCREAMING_SNAKE_CASE : int = nn.Linear(__lowerCamelCase , __lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Optional[Any]: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) _SCREAMING_SNAKE_CASE : Optional[Any] = self.mlp(__lowerCamelCase ) return logits
325
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase__ ={ 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ =[ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys UpperCamelCase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
325
1