code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def __lowercase ( snake_case = N ): """simple docstring""" __magic_name__ :Optional[int] = -sys.maxsize - 1 for i in range(len(snake_case ) - 1_2 ): __magic_name__ :List[Any] = 1 for j in range(1_3 ): product *= int(n[i + j] ) if product > largest_product: __magic_name__ :str = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
0
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
0
import math def _A ( _lowercase , _lowercase ) -> float: """simple docstring""" return math.pow(_lowercase , 2 ) - a def _A ( _lowercase ) -> float: """simple docstring""" return 2 * x def _A ( _lowercase ) -> float: """simple docstring""" __UpperCamelCase = 2.0 while start <= a: __UpperCamelCase = math.pow(_lowercase , 2 ) return start def _A ( _lowercase , _lowercase = 99_99 , _lowercase = 0.00_00_00_00_00_00_01 ) -> float: """simple docstring""" if a < 0: raise ValueError('math domain error' ) __UpperCamelCase = get_initial_point(_lowercase ) for _ in range(_lowercase ): __UpperCamelCase = value __UpperCamelCase = value - fx(_lowercase , _lowercase ) / fx_derivative(_lowercase ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''sew-d''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=("p2c", "c2p") , SCREAMING_SNAKE_CASE__ : str="layer_norm" , SCREAMING_SNAKE_CASE__ : Tuple="gelu_python" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-7 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Optional[int]="group" , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : str=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2_8 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]="mean" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=2_5_6 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = hidden_size __a : Optional[Any] = feat_extract_norm __a : List[str] = feat_extract_activation __a : Dict = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = list(SCREAMING_SNAKE_CASE__ ) __a : List[str] = list(SCREAMING_SNAKE_CASE__ ) __a : int = conv_bias __a : Tuple = num_conv_pos_embeddings __a : List[str] = num_conv_pos_embedding_groups __a : Optional[Any] = len(self.conv_dim ) __a : Union[str, Any] = num_hidden_layers __a : Optional[Any] = intermediate_size __a : Union[str, Any] = squeeze_factor __a : List[Any] = max_position_embeddings __a : Tuple = position_buckets __a : Optional[int] = share_att_key __a : List[str] = relative_attention __a : Any = norm_rel_ebd __a : Any = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = hidden_act __a : str = num_attention_heads __a : Union[str, Any] = hidden_dropout __a : Optional[int] = attention_dropout __a : List[str] = activation_dropout __a : int = feat_proj_dropout __a : int = final_dropout __a : Dict = layer_norm_eps __a : Tuple = feature_layer_norm_eps __a : str = initializer_range __a : Tuple = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : Tuple = apply_spec_augment __a : Optional[Any] = mask_time_prob __a : Any = mask_time_length __a : List[str] = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Tuple = mask_feature_length __a : Any = mask_feature_min_masks # ctc loss __a : Optional[int] = ctc_loss_reduction __a : List[Any] = ctc_zero_infinity # sequence classification __a : Dict = use_weighted_layer_sum __a : Optional[Any] = classifier_proj_size @property def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
47
0
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger UpperCAmelCase_ = get_logger(__name__) UpperCAmelCase_ = r""" Args: input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search kwargs (`Dict[str, Any]`, *optional*): Additional logits processor specific kwargs. Return: `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores. """ class lowerCamelCase__ : """simple docstring""" @add_start_docstrings(__lowerCAmelCase ) def __call__( self : List[Any] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCamelCase__ : """simple docstring""" @add_start_docstrings(__lowerCAmelCase ) def __call__( self : List[str] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCamelCase__ ( _A): """simple docstring""" @add_start_docstrings(__lowerCAmelCase ) def __call__( self : Optional[int] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int , **__lowerCAmelCase : Tuple ) -> jnp.ndarray: for processor in self: _A = inspect.signature(processor.__call__ ).parameters if len(__lowerCAmelCase ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( f'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' f'''{processor.__class__} are passed to the logits processor.''' ) _A = processor(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) else: _A = processor(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : Union[str, Any] , __lowerCAmelCase : float ) -> Tuple: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not (temperature > 0): raise ValueError(f'''`temperature` has to be a strictly positive float, but is {temperature}''' ) _A = temperature def __call__( self : Optional[int] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A = scores / self.temperature return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : str , __lowerCAmelCase : float , __lowerCAmelCase : float = -float('''Inf''' ) , __lowerCAmelCase : int = 1 ) -> Any: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or (top_p < 0 or top_p > 1.0): raise ValueError(f'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or (min_tokens_to_keep < 1): raise ValueError(f'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) _A = top_p _A = filter_value _A = min_tokens_to_keep def __call__( self : str , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A , _A = lax.top_k(__lowerCAmelCase , scores.shape[-1] ) _A = jnp.full_like(__lowerCAmelCase , self.filter_value ) _A = jax.nn.softmax(__lowerCAmelCase , axis=-1 ).cumsum(axis=-1 ) _A = cumulative_probs < self.top_p # include the token that is higher than top_p as well _A = jnp.roll(__lowerCAmelCase , 1 ) score_mask |= score_mask.at[:, 0].set(__lowerCAmelCase ) # min tokens to keep _A = score_mask.at[:, : self.min_tokens_to_keep].set(__lowerCAmelCase ) _A = jnp.where(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) _A = jax.lax.sort_key_val(__lowerCAmelCase , __lowerCAmelCase )[-1] return next_scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : Optional[Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = -float('''Inf''' ) , __lowerCAmelCase : int = 1 ) -> Optional[Any]: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or top_k <= 0: raise ValueError(f'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) _A = max(__lowerCAmelCase , __lowerCAmelCase ) _A = filter_value def __call__( self : Union[str, Any] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A , _A = scores.shape _A = jnp.full(batch_size * vocab_size , self.filter_value ) _A = min(self.top_k , scores.shape[-1] ) # Safety check _A , _A = lax.top_k(__lowerCAmelCase , __lowerCAmelCase ) _A = jnp.broadcast_to((jnp.arange(__lowerCAmelCase ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() _A = topk_scores.flatten() _A = topk_indices.flatten() + shift _A = next_scores_flat.at[topk_indices_flat].set(__lowerCAmelCase ) _A = next_scores_flat.reshape(__lowerCAmelCase , __lowerCAmelCase ) return next_scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : str , __lowerCAmelCase : int ) -> int: _A = bos_token_id def __call__( self : Union[str, Any] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A = jnp.full(scores.shape , -float('''inf''' ) ) _A = 1 - jnp.bool_(cur_len - 1 ) _A = jnp.where(__lowerCAmelCase , new_scores.at[:, self.bos_token_id].set(0 ) , __lowerCAmelCase ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : int , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> Any: _A = max_length _A = eos_token_id def __call__( self : List[str] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A = jnp.full(scores.shape , -float('''inf''' ) ) _A = 1 - jnp.bool_(cur_len - self.max_length + 1 ) _A = jnp.where(__lowerCAmelCase , new_scores.at[:, self.eos_token_id].set(0 ) , __lowerCAmelCase ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> Any: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or min_length < 0: raise ValueError(f'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or eos_token_id < 0: raise ValueError(f'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) _A = min_length _A = eos_token_id def __call__( self : Dict , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: # create boolean flag to decide if min length penalty should be applied _A = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) _A = jnp.where(__lowerCAmelCase , scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) , __lowerCAmelCase ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] ) -> Union[str, Any]: _A = list(__lowerCAmelCase ) _A = begin_index def __call__( self : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> Optional[Any]: _A = 1 - jnp.bool_(cur_len - self.begin_index ) _A = jnp.where(__lowerCAmelCase , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) , __lowerCAmelCase ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : int , __lowerCAmelCase : list ) -> Dict: _A = list(__lowerCAmelCase ) def __call__( self : str , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: _A = scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : int , __lowerCAmelCase : Optional[Any] ) -> List[Any]: _A = dict(__lowerCAmelCase ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. _A = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: _A = force_token_array.at[index].set(__lowerCAmelCase ) _A = jnp.intaa(__lowerCAmelCase ) def __call__( self : Optional[Any] , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int ) -> jnp.ndarray: def _force_token(__lowerCAmelCase : List[Any] ): _A = scores.shape[0] _A = self.force_token_array[generation_idx] _A = jnp.ones_like(__lowerCAmelCase , dtype=scores.dtype ) * -float('''inf''' ) _A = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) _A = lax.dynamic_update_slice(__lowerCAmelCase , __lowerCAmelCase , (0, current_token) ) return new_scores _A = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(__lowerCAmelCase ) , lambda: scores , ) , ) return scores class lowerCamelCase__ ( _A): """simple docstring""" def __init__( self : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] ) -> int: _A = generate_config.eos_token_id _A = generate_config.no_timestamps_token_id _A = generate_config.no_timestamps_token_id + 1 _A = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(__lowerCAmelCase , '''max_initial_timestamp_index''' ): _A = generate_config.max_initial_timestamp_index else: _A = model_config.vocab_size if self.max_initial_timestamp_index is None: _A = model_config.vocab_size def __call__( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] ) -> Union[str, Any]: # suppress <|notimestamps|> which is handled by without_timestamps _A = scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(__lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ): _A = jnp.where((cur_len - self.begin_index) >= 1 , __lowerCAmelCase , __lowerCAmelCase ) _A = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , __lowerCAmelCase , ) _A = jnp.where((cur_len - self.begin_index) < 2 , __lowerCAmelCase , __lowerCAmelCase ) _A = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , __lowerCAmelCase , __lowerCAmelCase , ) return jnp.where( __lowerCAmelCase , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) , ) , __lowerCAmelCase , ) _A = jax.vmap(__lowerCAmelCase )(__lowerCAmelCase , __lowerCAmelCase ) _A = jnp.where(cur_len == self.begin_index , __lowerCAmelCase , __lowerCAmelCase ) _A = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , __lowerCAmelCase , ) _A = self.timestamp_begin + self.max_initial_timestamp_index _A = jnp.where( __lowerCAmelCase , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) , __lowerCAmelCase , ) # if sum of probability over timestamps is above any other token, sample timestamp _A = jax.nn.log_softmax(__lowerCAmelCase , axis=-1 ) def handle_cumulative_probs(__lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str ): _A = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) _A = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) , __lowerCAmelCase , ) _A = jax.vmap(__lowerCAmelCase )(__lowerCAmelCase , __lowerCAmelCase ) return scores
2
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_ , A_ )-> Any: '''simple docstring''' UpperCamelCase = dataset UpperCamelCase = process UpperCamelCase = params def __len__( self )-> Optional[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self , A_ )-> List[Any]: '''simple docstring''' UpperCamelCase = self.dataset[i] UpperCamelCase = self.process(A_ , **self.params ) return processed class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_ , A_ , A_=None )-> Optional[Any]: '''simple docstring''' UpperCamelCase = loader UpperCamelCase = infer UpperCamelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether UpperCamelCase = None UpperCamelCase = loader_batch_size # Internal bookkeeping UpperCamelCase = None UpperCamelCase = None def __len__( self )-> Tuple: '''simple docstring''' return len(self.loader ) def __iter__( self )-> Tuple: '''simple docstring''' UpperCamelCase = iter(self.loader ) return self def UpperCAmelCase_ ( self )-> Union[str, Any]: '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice UpperCamelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) UpperCamelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(A_ , A_ ): # Convert ModelOutput to tuple first UpperCamelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(A_ , A_ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around UpperCamelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. UpperCamelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 UpperCamelCase = self._loader_batch_data.__class__(A_ ) self._loader_batch_index += 1 return result def UpperCAmelCase_ ( self )-> str: '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch UpperCamelCase = next(self.iterator ) UpperCamelCase = self.infer(A_ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(A_ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(A_ , A_ ): UpperCamelCase = len(A_ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size # Setting internal index to unwrap the batch UpperCamelCase = processed UpperCamelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_ , A_ , A_=None )-> Union[str, Any]: '''simple docstring''' super().__init__(A_ , A_ , A_ ) def __iter__( self )-> str: '''simple docstring''' UpperCamelCase = iter(self.loader ) UpperCamelCase = None return self def UpperCAmelCase_ ( self )-> Optional[int]: '''simple docstring''' if self.subiterator is None: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item UpperCamelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) UpperCamelCase = next(self.subiterator ) return processed class SCREAMING_SNAKE_CASE__ ( snake_case_): def __iter__( self )-> Union[str, Any]: '''simple docstring''' UpperCamelCase = iter(self.loader ) return self def UpperCAmelCase_ ( self )-> List[Any]: '''simple docstring''' UpperCamelCase = False UpperCamelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop('is_last' ) accumulator.append(A_ ) if is_last: return accumulator while not is_last: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(A_ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(A_ , A_ ): UpperCamelCase = len(A_ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size UpperCamelCase = processed UpperCamelCase = 0 while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop('is_last' ) accumulator.append(A_ ) if is_last: return accumulator else: UpperCamelCase = processed UpperCamelCase = item.pop('is_last' ) accumulator.append(A_ ) return accumulator class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_ )-> int: '''simple docstring''' UpperCamelCase = dataset UpperCamelCase = key def __len__( self )-> str: '''simple docstring''' return len(self.dataset ) def __getitem__( self , A_ )-> Tuple: '''simple docstring''' return self.dataset[i][self.key] class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_ , A_ )-> Any: '''simple docstring''' UpperCamelCase = dataset UpperCamelCase = keya UpperCamelCase = keya def __len__( self )-> List[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self , A_ )-> List[Any]: '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
3
from collections.abc import Sequence from queue import Queue class _UpperCamelCase: def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None ): '''simple docstring''' __a : Tuple = start __a : Dict = end __a : List[str] = val __a : List[Any] = (start + end) // 2 __a : Optional[Any] = left __a : List[str] = right def __repr__( self : Dict ): '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class _UpperCamelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Sequence , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Tuple = collection __a : Dict = function if self.collection: __a : int = self._build_tree(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.collection[start] ) __a : Tuple = (start + end) // 2 __a : Optional[int] = self._build_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Tuple = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE__ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if node.start == i and node.end == i: __a : Optional[Any] = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = self.fn(node.left.val , node.right.val ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE__ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE__ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' if self.root is not None: __a : Tuple = Queue() queue.put(self.root ) while not queue.empty(): __a : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) SCREAMING_SNAKE_CASE__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
47
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class a ( a__ ): snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
4
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int SCREAMING_SNAKE_CASE__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _UpperCamelCase( datasets.BuilderConfig ): __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None def UpperCAmelCase__ ( lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[int] , ): import pyspark def generate_fn(): __a : List[Any] = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __a : Optional[int] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __a : Optional[Any] = partition_df.collect() __a : Union[str, Any] = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _UpperCamelCase( _BaseExamplesIterable ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : Dict=None , ): '''simple docstring''' __a : List[str] = df __a : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) __a : List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.random.Generator ): '''simple docstring''' __a : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return len(self.partition_order ) class _UpperCamelCase( datasets.DatasetBuilder ): __SCREAMING_SNAKE_CASE : List[str] = SparkConfig def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' import pyspark __a : int = pyspark.sql.SparkSession.builder.getOrCreate() __a : Optional[int] = df __a : List[Any] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__ : List[str] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE__ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __a : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE__ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE__ : int ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __a : List[str] = self.df.count() __a : Dict = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __a : List[str] = ( self.df.limit(SCREAMING_SNAKE_CASE__ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE__ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __a : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __a : Union[str, Any] = min(SCREAMING_SNAKE_CASE__ , int(approx_total_size / max_shard_size ) ) __a : int = self.df.repartition(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , ): '''simple docstring''' import pyspark __a : Any = ParquetWriter if file_format == 'parquet' else ArrowWriter __a : Union[str, Any] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) if self._working_dir else fpath __a : Optional[int] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __a : List[str] = self.config.features __a : int = self._writer_batch_size __a : Union[str, Any] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __a : Any = pyspark.TaskContext().taskAttemptId() __a : str = next(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __a : Any = 0 __a : List[str] = writer_class( features=SCREAMING_SNAKE_CASE__ , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __a , __a : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __a : Optional[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Union[str, Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) if writer._num_bytes > 0: __a , __a : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ): __a : Any = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ) , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) shutil.move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE__ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , SCREAMING_SNAKE_CASE__ : str = "arrow" , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' self._validate_cache_dir() __a : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = not is_remote_filesystem(self._fs ) __a : Optional[Any] = os.path.join if is_local else posixpath.join __a : Any = '-TTTTT-SSSSS-of-NNNNN' __a : Union[str, Any] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __a : Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE__ ) __a : Any = 0 __a : Dict = 0 __a : int = 0 __a : List[str] = [] __a : Optional[int] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE__ ) __a : List[str] = total_num_examples __a : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __a : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __a : Dict = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): rename( SCREAMING_SNAKE_CASE__ , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __a : Union[str, Any] = [] __a : List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a , __a : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE__ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ).map(lambda SCREAMING_SNAKE_CASE__ : _rename_shard(*SCREAMING_SNAKE_CASE__ ) ).collect() else: # don't use any pattern __a : List[Any] = 0 __a : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE__ , '' ) , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
47
0
'''simple docstring''' from typing import Dict from .base import GenericTensor, Pipeline class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def _lowercase ( self , _lowercase=None , _lowercase=None , _lowercase=None , **_lowercase ): """simple docstring""" if tokenize_kwargs is None: _lowerCAmelCase = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) _lowerCAmelCase = truncation _lowerCAmelCase = tokenize_kwargs _lowerCAmelCase = {} if return_tensors is not None: _lowerCAmelCase = return_tensors return preprocess_params, {}, postprocess_params def _lowercase ( self , _lowercase , **_lowercase ): """simple docstring""" _lowerCAmelCase = self.framework _lowerCAmelCase = self.tokenizer(_lowercase , return_tensors=_lowercase , **_lowercase ) return model_inputs def _lowercase ( self , _lowercase ): """simple docstring""" _lowerCAmelCase = self.model(**_lowercase ) return model_outputs def _lowercase ( self , _lowercase , _lowercase=False ): """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self , *_lowercase , **_lowercase ): """simple docstring""" return super().__call__(*_lowercase , **_lowercase )
5
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : int ): # save results if os.path.exists(lowerCamelCase_ ): if os.path.exists(os.path.join(lowerCamelCase_ , 'config.json' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'config.json' ) ): os.remove(os.path.join(lowerCamelCase_ , 'config.json' ) ) if os.path.exists(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ): os.remove(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) else: os.makedirs(lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : Any=False ): __a : Dict = 2 if unlogit: __a : Optional[Any] = torch.pow(lowerCamelCase_ , lowerCamelCase_ ) __a : Any = p * torch.log(lowerCamelCase_ ) __a : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ ( lowerCamelCase_ : Any ): logger.info('lv, h >\t' + '\t'.join(f'''{x + 1}''' for x in range(len(lowerCamelCase_ ) ) ) ) for row in range(len(lowerCamelCase_ ) ): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:d}''' for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=False ): __a , __a : Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads __a : str = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) __a : int = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) if head_mask is None: __a : Union[str, Any] = torch.ones(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCamelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __a : Any = None __a : Optional[int] = 0.0 __a : Optional[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCamelCase_ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __a : Dict = tuple(t.to(args.device ) for t in inputs ) ((__a) , ) : Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __a : List[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ , head_mask=lowerCamelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __a , __a , __a : int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCamelCase_ ): __a : List[str] = entropy(attn.detach() , lowerCamelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCamelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __a : Optional[Any] = 2 __a : Union[str, Any] = torch.pow(torch.pow(lowerCamelCase_ , lowerCamelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: __a : List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(lowerCamelCase_ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(lowerCamelCase_ ) logger.info('Head ranked by importance scores' ) __a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __a : str = torch.arange( head_importance.numel() , device=args.device ) __a : Tuple = head_ranks.view_as(lowerCamelCase_ ) print_ad_tensor(lowerCamelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): __a , __a , __a : Optional[int] = compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ ) __a : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , lowerCamelCase_ , original_score * args.masking_threshold ) __a : Tuple = torch.ones_like(lowerCamelCase_ ) __a : int = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __a : Tuple = original_score while current_score >= original_score * args.masking_threshold: __a : Optional[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __a : List[str] = float('Inf' ) __a : List[Any] = head_importance.view(-1 ).sort()[1] if len(lowerCamelCase_ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __a : Any = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __a : int = new_head_mask.view(-1 ) __a : Tuple = 0.0 __a : int = new_head_mask.view_as(lowerCamelCase_ ) __a : Optional[int] = new_head_mask.clone().detach() print_ad_tensor(lowerCamelCase_ ) # Compute metric and head importance again __a , __a , __a : int = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[Any] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowerCamelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(lowerCamelCase_ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): __a : List[Any] = datetime.now() __a , __a , __a : List[str] = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[str] = 1 / loss __a : List[Any] = datetime.now() - before_time __a : List[str] = sum(p.numel() for p in model.parameters() ) __a : Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __a : Tuple = [ v, ] assert sum(len(lowerCamelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCamelCase_ ) __a : Optional[Any] = sum(p.numel() for p in model.parameters() ) __a : Tuple = datetime.now() __a , __a , __a : Tuple = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ , actually_pruned=lowerCamelCase_ , ) __a : Optional[Any] = 1 / loss __a : List[Any] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowerCamelCase_ , lowerCamelCase_ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , lowerCamelCase_ , lowerCamelCase_ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(lowerCamelCase_ , args.output_dir ) def UpperCAmelCase__ ( ): __a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=lowerCamelCase_ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=lowerCamelCase_ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=lowerCamelCase_ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=lowerCamelCase_ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=lowerCamelCase_ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=lowerCamelCase_ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=lowerCamelCase_ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=lowerCamelCase_ , help='Batch size.' ) parser.add_argument('--seed' , type=lowerCamelCase_ , default=4_2 ) parser.add_argument('--local_rank' , type=lowerCamelCase_ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) __a : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCamelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __a : List[str] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __a : Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __a : Union[str, Any] = torch.device('cuda' , args.local_rank ) __a : Any = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __a : Optional[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __a : List[Any] = nn.parallel.DistributedDataParallel( lowerCamelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCamelCase_ ) elif args.n_gpu > 1: __a : Union[str, Any] = nn.DataParallel(lowerCamelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , lowerCamelCase_ ) # Prepare dataset __a : Tuple = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __a : str = (torch.from_numpy(lowerCamelCase_ ),) __a : List[str] = TensorDataset(*lowerCamelCase_ ) __a : Optional[Any] = RandomSampler(lowerCamelCase_ ) __a : Union[str, Any] = DataLoader(lowerCamelCase_ , sampler=lowerCamelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __a : Union[str, Any] = mask_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) prune_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
47
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: _lowerCamelCase = None _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), }, 'tokenizer_file': { 'google/bigbird-roberta-base': ( 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json' ), 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } _lowerCamelCase = '▁' class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = BigBirdTokenizer lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = [] def __init__( self :str , __A :Tuple=None , __A :Optional[Any]=None , __A :Any="<unk>" , __A :Any="<s>" , __A :Union[str, Any]="</s>" , __A :List[str]="<pad>" , __A :Optional[Any]="[SEP]" , __A :str="[MASK]" , __A :Optional[Any]="[CLS]" , **__A :Union[str, Any] , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( __A , tokenizer_file=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , **__A , ) SCREAMING_SNAKE_CASE__ = vocab_file SCREAMING_SNAKE_CASE__ = False if not self.vocab_file else True def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self :Optional[int] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1] + ([0] * len(__A )) + [1] def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ): copyfile(self.vocab_file , __A ) return (out_vocab_file,)
6
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __a : List[Any] = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1_0_2_4, 'hidden_size': 7_6_8, 'max_length': 5_1_2, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1_0_2_4, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __a : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a : List[str] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a : int = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __a : Optional[Any] = os.path.join(get_home_dir() , 'models' ) __a : Optional[Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __a : Any = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __a : Dict = original_bort._collect_params_with_prefix() # Build our config 🤗 __a : Optional[Any] = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(lowerCamelCase_ ), } __a : str = BertConfig.from_dict(lowerCamelCase_ ) __a : Optional[int] = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Optional[Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __a : Optional[int] = hf_param.shape __a : int = to_torch(params[gluon_param] ) __a : int = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __a : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __a : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __a : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __a : BertSelfAttention = layer.attention.self __a : Optional[int] = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a : str = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a : str = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a : Dict = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a : str = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a : BertSelfOutput = layer.attention.output __a : Tuple = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a : Dict = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a : BertIntermediate = layer.intermediate __a : List[str] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a : Optional[Any] = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a : BertOutput = layer.output __a : str = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a : List[Any] = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a : List[str] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a : Union[str, Any] = RobertaTokenizer.from_pretrained('roberta-base' ) __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ )['input_ids'] # Get gluon output __a : Optional[int] = mx.nd.array([input_ids] ) __a : Tuple = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __a : Optional[Any] = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ , return_tensors='pt' ) __a : int = hf_bort_model(**lowerCamelCase_ )[0] __a : Dict = output_gluon[0].asnumpy() __a : str = output_hf[0].detach().numpy() __a : List[Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a : str = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
47
0
"""simple docstring""" def _snake_case ( _snake_case : Dict ) -> Tuple: '''simple docstring''' _A = len(_snake_case ) for i in range(length - 1 ): _A = i for k in range(i + 1 , _snake_case ): if collection[k] < collection[least]: _A = k if least != i: _A , _A = (collection[i], collection[least]) return collection if __name__ == "__main__": a = input('''Enter numbers separated by a comma:\n''').strip() a = [int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
7
def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ): __a : Any = '' for i in table: res += inp[i - 1] return res def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] ): return data[1:] + data[0] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): __a : Optional[int] = '' for i in range(len(lowerCamelCase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): __a : List[str] = int('0b' + data[0] + data[-1] , 2 ) __a : List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = message[:4] __a : str = message[4:] __a : Any = apply_table(lowerCamelCase_ , lowerCamelCase_ ) __a : int = xor(lowerCamelCase_ , lowerCamelCase_ ) __a : Dict = apply_sbox(lowerCamelCase_ , temp[:4] ) # noqa: E741 __a : Tuple = apply_sbox(lowerCamelCase_ , temp[4:] ) __a : List[Any] = '0' * (2 - len(lowerCamelCase_ )) + l # noqa: E741 __a : List[str] = '0' * (2 - len(lowerCamelCase_ )) + r __a : List[Any] = apply_table(l + r , lowerCamelCase_ ) __a : Dict = xor(lowerCamelCase_ , lowerCamelCase_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE__ = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE__ = [6, 3, 7, 4, 8, 5, 10, 9] SCREAMING_SNAKE_CASE__ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] SCREAMING_SNAKE_CASE__ = [2, 4, 3, 1] SCREAMING_SNAKE_CASE__ = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE__ = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE__ = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE__ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE__ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE__ = apply_table(key, paa_table) SCREAMING_SNAKE_CASE__ = temp[:5] SCREAMING_SNAKE_CASE__ = temp[5:] SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE__ = apply_table(message, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE__ = apply_table(CT, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
47
0
'''simple docstring''' def _lowerCAmelCase ( __snake_case : int = 10 ) -> str: if not isinstance(__snake_case , __snake_case ) or n < 0: raise ValueError('Invalid input' ) __A : Optional[Any] = 10**n __A : List[str] = 2_84_33 * (pow(2 , 7_83_04_57 , __snake_case )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
8
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
0
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" A__ : Union[str, Any] = "trajectory_transformer" A__ : List[str] = ["past_key_values"] A__ : Dict = { "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Dict , _snake_case : List[Any]=1_00 , _snake_case : Union[str, Any]=5 , _snake_case : Dict=1 , _snake_case : Any=1 , _snake_case : Any=2_49 , _snake_case : Any=6 , _snake_case : Optional[int]=17 , _snake_case : int=25 , _snake_case : List[str]=4 , _snake_case : Any=4 , _snake_case : Union[str, Any]=1_28 , _snake_case : Any=0.1 , _snake_case : Any=0.1 , _snake_case : Tuple=0.1 , _snake_case : Tuple=0.0006 , _snake_case : Tuple=5_12 , _snake_case : Dict=0.02 , _snake_case : Dict=1E-12 , _snake_case : str=1 , _snake_case : Dict=True , _snake_case : List[str]=1 , _snake_case : str=5_02_56 , _snake_case : List[str]=5_02_56 , **_snake_case : Optional[Any] , ): """simple docstring""" A__ = vocab_size A__ = action_weight A__ = reward_weight A__ = value_weight A__ = max_position_embeddings A__ = block_size A__ = action_dim A__ = observation_dim A__ = transition_dim A__ = learning_rate A__ = n_layer A__ = n_head A__ = n_embd A__ = embd_pdrop A__ = attn_pdrop A__ = resid_pdrop A__ = initializer_range A__ = layer_norm_eps A__ = kaiming_initializer_range A__ = use_cache super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case )
9
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''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 _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''roberta''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : str=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = vocab_size __a : Tuple = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : str = hidden_act __a : Optional[Any] = intermediate_size __a : Dict = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Dict = type_vocab_size __a : str = initializer_range __a : List[str] = layer_norm_eps __a : Optional[int] = position_embedding_type __a : Union[str, Any] = use_cache __a : str = classifier_dropout class _UpperCamelCase( __lowerCamelCase ): @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' if self.task == "multiple-choice": __a : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
0
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCAmelCase_ ( __lowercase ): def __init__( self : int , _A : Optional[int] , _A : Dict , _A : Union[str, Any] ): _UpperCamelCase = dataset _UpperCamelCase = process _UpperCamelCase = params def __len__( self : Optional[Any] ): return len(self.dataset ) def __getitem__( self : Any , _A : Union[str, Any] ): _UpperCamelCase = self.dataset[i] _UpperCamelCase = self.process(_A , **self.params ) return processed class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[str] , _A : Union[str, Any] , _A : List[Any] , _A : Optional[int] , _A : Any=None ): _UpperCamelCase = loader _UpperCamelCase = infer _UpperCamelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether _UpperCamelCase = None _UpperCamelCase = loader_batch_size # Internal bookkeeping _UpperCamelCase = None _UpperCamelCase = None def __len__( self : str ): return len(self.loader ) def __iter__( self : str ): _UpperCamelCase = iter(self.loader ) return self def UpperCamelCase_ ( self : List[str] ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice _UpperCamelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) _UpperCamelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(_A , _A ): # Convert ModelOutput to tuple first _UpperCamelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): _UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_A , _A ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): _UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around _UpperCamelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCamelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCamelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. _UpperCamelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 _UpperCamelCase = self._loader_batch_data.__class__(_A ) self._loader_batch_index += 1 return result def UpperCamelCase_ ( self : Dict ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch _UpperCamelCase = next(self.iterator ) _UpperCamelCase = self.infer(_A , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_A , torch.Tensor ): _UpperCamelCase = processed else: _UpperCamelCase = list(processed.keys() )[0] _UpperCamelCase = processed[key] if isinstance(_A , _A ): _UpperCamelCase = len(_A ) else: _UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCamelCase = observed_batch_size # Setting internal index to unwrap the batch _UpperCamelCase = processed _UpperCamelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowerCAmelCase_ ( __lowercase ): def __init__( self : str , _A : Dict , _A : List[str] , _A : str , _A : int=None ): super().__init__(_A , _A , _A ) def __iter__( self : Optional[int] ): _UpperCamelCase = iter(self.loader ) _UpperCamelCase = None return self def UpperCamelCase_ ( self : Optional[int] ): if self.subiterator is None: _UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item _UpperCamelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators _UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) _UpperCamelCase = next(self.subiterator ) return processed class lowerCAmelCase_ ( __lowercase ): def __iter__( self : Optional[Any] ): _UpperCamelCase = iter(self.loader ) return self def UpperCamelCase_ ( self : Union[str, Any] ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. _UpperCamelCase = False _UpperCamelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: _UpperCamelCase = self.loader_batch_item() _UpperCamelCase = item.pop('''is_last''' ) accumulator.append(_A ) if is_last: return accumulator while not is_last: _UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_A , torch.Tensor ): _UpperCamelCase = processed else: _UpperCamelCase = list(processed.keys() )[0] _UpperCamelCase = processed[key] if isinstance(_A , _A ): _UpperCamelCase = len(_A ) else: _UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCamelCase = observed_batch_size _UpperCamelCase = processed _UpperCamelCase = 0 while self._loader_batch_index < self.loader_batch_size: _UpperCamelCase = self.loader_batch_item() _UpperCamelCase = item.pop('''is_last''' ) accumulator.append(_A ) if is_last: return accumulator else: _UpperCamelCase = processed _UpperCamelCase = item.pop('''is_last''' ) accumulator.append(_A ) return accumulator class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[str] , _A : Dataset , _A : str ): _UpperCamelCase = dataset _UpperCamelCase = key def __len__( self : List[str] ): return len(self.dataset ) def __getitem__( self : Tuple , _A : Union[str, Any] ): return self.dataset[i][self.key] class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , _A : Dataset , _A : str , _A : str ): _UpperCamelCase = dataset _UpperCamelCase = keya _UpperCamelCase = keya def __len__( self : List[str] ): return len(self.dataset ) def __getitem__( self : Optional[int] , _A : Any ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
10
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''▁''' SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } SCREAMING_SNAKE_CASE__ = { '''facebook/xglm-564M''': 2048, } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="<unk>" , SCREAMING_SNAKE_CASE__ : Dict="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer __a : Any = 7 __a : Union[str, Any] = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words )] __a : Union[str, Any] = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) __a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Any = 1 # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __a : List[str] = len(self.sp_model ) __a : Optional[int] = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) __a : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[str] ): '''simple docstring''' __a : Tuple = self.__dict__.copy() __a : List[str] = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Dict = {} __a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a __a : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowercase_ = ( "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) ) lowercase_ = ( ("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"), ) lowercase_ = ( ("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), ) lowercase_ = ( ("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), ) lowercase_ = ( ("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]), ) lowercase_ = ( ("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), ) lowercase_ = ( ("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 (): """simple docstring""" _a , _a = randrange(len(__A)), randrange(len(__A)) _a = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] _a , _a = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCAmelCase (__A = 100): """simple docstring""" return (generate_random_hand() for _ in range(__A)) @pytest.mark.parametrize('''hand, expected''' , __A) def lowerCAmelCase (__A , __A): """simple docstring""" assert PokerHand(__A)._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , __A) def lowerCAmelCase (__A , __A): """simple docstring""" assert PokerHand(__A)._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , __A) def lowerCAmelCase (__A , __A , __A): """simple docstring""" _a = PokerHand(__A) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , __A) def lowerCAmelCase (__A , __A): """simple docstring""" assert PokerHand(__A)._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , __A) def lowerCAmelCase (__A , __A): """simple docstring""" assert PokerHand(__A)._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , __A) def lowerCAmelCase (__A , __A , __A): """simple docstring""" assert PokerHand(__A).compare_with(PokerHand(__A)) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands()) def lowerCAmelCase (__A , __A , __A): """simple docstring""" assert PokerHand(__A).compare_with(PokerHand(__A)) == expected def lowerCAmelCase (): """simple docstring""" _a = [PokerHand(__A) for hand in SORTED_HANDS] _a = poker_hands.copy() shuffle(__A) _a = chain(sorted(__A)) for index, hand in enumerate(__A): assert hand == poker_hands[index] def lowerCAmelCase (): """simple docstring""" _a = [PokerHand('''2D AC 3H 4H 5S'''), PokerHand('''2S 3H 4H 5S 6C''')] pokerhands.sort(reverse=__A) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCAmelCase (): """simple docstring""" _a = PokerHand('''2C 4S AS 3D 5C''') _a = True _a = [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 (): """simple docstring""" _a = 0 _a = os.path.abspath(os.path.dirname(__A)) _a = os.path.join(__A , '''poker_hands.txt''') with open(__A) as file_hand: for line in file_hand: _a = line[:14].strip() _a = line[15:].strip() _a , _a = PokerHand(__A), PokerHand(__A) _a = player.compare_with(__A) if output == "Win": answer += 1 assert answer == 376
11
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] SCREAMING_SNAKE_CASE__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] ): __a : str = torch.load(lowerCamelCase_ , map_location='cpu' ) return sd def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict=rename_keys_prefix ): __a : Optional[Any] = OrderedDict() __a : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a : List[Any] = key for name_pair in rename_keys_prefix: __a : List[str] = new_key.replace(name_pair[0] , name_pair[1] ) __a : Any = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a : int = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : Any ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a : Dict = 'pretraining' if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __a : int = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __a : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} __a : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __a : Any = {'visual_embedding_dim': 2_0_4_8} __a : List[str] = 'vqa_advanced' elif "vqa" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __a : List[Any] = 'vqa' elif "nlvr" in checkpoint_path: __a : Optional[int] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __a : Optional[Any] = 'nlvr' __a : str = VisualBertConfig(**lowerCamelCase_ ) # Load State Dict __a : str = load_state_dict(lowerCamelCase_ ) __a : str = get_new_dict(lowerCamelCase_ , lowerCamelCase_ ) if model_type == "pretraining": __a : Optional[Any] = VisualBertForPreTraining(lowerCamelCase_ ) elif model_type == "vqa": __a : Any = VisualBertForQuestionAnswering(lowerCamelCase_ ) elif model_type == "nlvr": __a : int = VisualBertForVisualReasoning(lowerCamelCase_ ) elif model_type == "multichoice": __a : Optional[int] = VisualBertForMultipleChoice(lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # Save Checkpoints Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
47
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCamelCase__ : List[Any] = logging.get_logger(__name__) lowerCamelCase__ : Dict = { """post_extract_proj""": """feature_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.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Dict: '''simple docstring''' for attribute in key.split(""".""" ): lowercase__ : Union[str, Any] = getattr(lowercase_ , lowercase_ ) if weight_type is not None: lowercase__ : str = getattr(lowercase_ , lowercase_ ).shape else: lowercase__ : Any = 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": lowercase__ : Union[str, Any] = value elif weight_type == "weight_g": lowercase__ : str = value elif weight_type == "weight_v": lowercase__ : str = value elif weight_type == "bias": lowercase__ : Optional[int] = value else: lowercase__ : Any = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> List[Any]: '''simple docstring''' lowercase__ : List[Any] = [] lowercase__ : Union[str, Any] = fairseq_model.state_dict() lowercase__ : Any = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): lowercase__ : Optional[int] = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == """group""" , ) lowercase__ : str = True else: for key, mapped_key in MAPPING.items(): lowercase__ : Optional[int] = """sew.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: lowercase__ : Tuple = True if "*" in mapped_key: lowercase__ : Optional[Any] = name.split(lowercase_ )[0].split(""".""" )[-2] lowercase__ : Optional[Any] = mapped_key.replace("""*""" , lowercase_ ) if "weight_g" in name: lowercase__ : Optional[int] = """weight_g""" elif "weight_v" in name: lowercase__ : Dict = """weight_v""" elif "weight" in name: lowercase__ : List[str] = """weight""" elif "bias" in name: lowercase__ : str = """bias""" else: lowercase__ : List[Any] = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F'Unused weights: {unused_weights}' ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> List[Any]: '''simple docstring''' lowercase__ : int = full_name.split("""conv_layers.""" )[-1] lowercase__ : int = name.split(""".""" ) lowercase__ : Union[str, Any] = int(items[0] ) lowercase__ : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) lowercase__ : 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.' ) lowercase__ : Tuple = 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." ) lowercase__ : Union[str, 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.' ) lowercase__ : Optional[Any] = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowercase_ ) def UpperCamelCase ( lowercase_ , lowercase_ ) -> Optional[Any]: '''simple docstring''' lowercase__ : Optional[Any] = SEWConfig() if is_finetuned: lowercase__ : Any = model.wav_encoder.wav_model.cfg else: lowercase__ : Dict = model.cfg lowercase__ : Optional[Any] = fs_config.conv_bias lowercase__ : Tuple = eval(fs_config.conv_feature_layers ) lowercase__ : List[str] = [x[0] for x in conv_layers] lowercase__ : Dict = [x[1] for x in conv_layers] lowercase__ : Tuple = [x[2] for x in conv_layers] lowercase__ : List[str] = """gelu""" lowercase__ : Union[str, Any] = """layer""" if fs_config.extractor_mode == """layer_norm""" else """group""" lowercase__ : Union[str, Any] = 0.0 lowercase__ : Tuple = fs_config.activation_fn.name lowercase__ : Tuple = fs_config.encoder_embed_dim lowercase__ : List[str] = 0.02 lowercase__ : Optional[Any] = fs_config.encoder_ffn_embed_dim lowercase__ : Optional[Any] = 1E-5 lowercase__ : List[Any] = fs_config.encoder_layerdrop lowercase__ : Any = fs_config.encoder_attention_heads lowercase__ : Any = fs_config.conv_pos_groups lowercase__ : Dict = fs_config.conv_pos lowercase__ : List[Any] = len(lowercase_ ) lowercase__ : Union[str, Any] = fs_config.encoder_layers lowercase__ : Optional[Any] = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: lowercase__ : Optional[Any] = model.cfg lowercase__ : Union[str, Any] = fs_config.final_dropout lowercase__ : int = fs_config.layerdrop lowercase__ : int = fs_config.activation_dropout lowercase__ : Optional[Any] = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 lowercase__ : Tuple = fs_config.attention_dropout lowercase__ : Any = fs_config.dropout_input lowercase__ : Any = fs_config.dropout lowercase__ : Dict = fs_config.mask_channel_length lowercase__ : Optional[int] = fs_config.mask_channel_prob lowercase__ : Any = fs_config.mask_length lowercase__ : Dict = fs_config.mask_prob lowercase__ : Dict = """Wav2Vec2FeatureExtractor""" lowercase__ : List[Any] = """Wav2Vec2CTCTokenizer""" return config @torch.no_grad() def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=True ) -> int: '''simple docstring''' if is_finetuned: lowercase__ , lowercase__ , lowercase__ : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: lowercase__ , lowercase__ , lowercase__ : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: lowercase__ : Optional[Any] = SEWConfig.from_pretrained(lowercase_ ) else: lowercase__ : Optional[int] = convert_config(model[0] , lowercase_ ) lowercase__ : Dict = model[0].eval() lowercase__ : Any = True if config.feat_extract_norm == """layer""" else False lowercase__ : List[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=lowercase_ , return_attention_mask=lowercase_ , ) if is_finetuned: if dict_path: lowercase__ : Optional[int] = Dictionary.load(lowercase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowercase__ : List[Any] = target_dict.pad_index lowercase__ : int = target_dict.bos_index lowercase__ : Optional[Any] = target_dict.pad_index lowercase__ : List[str] = target_dict.bos_index lowercase__ : Optional[int] = target_dict.eos_index lowercase__ : Union[str, Any] = len(target_dict.symbols ) lowercase__ : Optional[int] = os.path.join(lowercase_ , """vocab.json""" ) if not os.path.isdir(lowercase_ ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowercase_ ) ) return os.makedirs(lowercase_ , exist_ok=lowercase_ ) with open(lowercase_ , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , lowercase_ ) lowercase__ : Optional[Any] = WavaVecaCTCTokenizer( lowercase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowercase_ , ) lowercase__ : Union[str, Any] = WavaVecaProcessor(feature_extractor=lowercase_ , tokenizer=lowercase_ ) processor.save_pretrained(lowercase_ ) lowercase__ : List[str] = SEWForCTC(lowercase_ ) else: lowercase__ : str = SEWModel(lowercase_ ) feature_extractor.save_pretrained(lowercase_ ) recursively_load_weights(lowercase_ , lowercase_ , lowercase_ ) hf_model.save_pretrained(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ : Any = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowerCamelCase__ : Optional[int] = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
12
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
47
0
'''simple docstring''' from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax A__ : Optional[int] = logging.get_logger(__name__) @add_end_docstrings(_UpperCAmelCase ) class UpperCAmelCase_ (_UpperCAmelCase ): """simple docstring""" def __init__( self , **SCREAMING_SNAKE_CASE_ ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return super().__call__(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: __lowerCamelCase : Dict = {} if "candidate_labels" in kwargs: __lowerCamelCase : List[str] = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: __lowerCamelCase : Tuple = kwargs['hypothesis_template'] return preprocess_params, {}, {} def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="This is a photo of {}." ) -> Tuple: __lowerCamelCase : Union[str, Any] = load_image(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = self.image_processor(images=[image] , return_tensors=self.framework ) __lowerCamelCase : Optional[Any] = candidate_labels __lowerCamelCase : int = [hypothesis_template.format(SCREAMING_SNAKE_CASE_ ) for x in candidate_labels] __lowerCamelCase : Union[str, Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : List[str] = [text_inputs] return inputs def lowercase_ ( self , SCREAMING_SNAKE_CASE_ ) -> Dict: __lowerCamelCase : Dict = model_inputs.pop('candidate_labels' ) __lowerCamelCase : int = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , SCREAMING_SNAKE_CASE_ ): __lowerCamelCase : List[Any] = text_inputs[0] else: # Batching case. __lowerCamelCase : Optional[Any] = text_inputs[0][0] __lowerCamelCase : Optional[int] = self.model(**SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_image, } return model_outputs def lowercase_ ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: __lowerCamelCase : str = model_outputs.pop('candidate_labels' ) __lowerCamelCase : Union[str, Any] = model_outputs['logits'][0] if self.framework == "pt": __lowerCamelCase : List[Any] = logits.softmax(dim=-1 ).squeeze(-1 ) __lowerCamelCase : Dict = probs.tolist() if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __lowerCamelCase : List[Any] = [scores] elif self.framework == "tf": __lowerCamelCase : Union[str, Any] = stable_softmax(SCREAMING_SNAKE_CASE_ , axis=-1 ) __lowerCamelCase : Optional[Any] = probs.numpy().tolist() else: raise ValueError(f'Unsupported framework: {self.framework}' ) __lowerCamelCase : Optional[Any] = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , key=lambda SCREAMING_SNAKE_CASE_ : -x[0] ) ] return result
13
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class _UpperCamelCase( __lowerCamelCase ): def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[Any] = tempfile.mkdtemp() __a : int = 8 # DPR tok __a : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , 'dpr_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_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] ) ) # BART tok __a : str = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __a : Optional[int] = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __a : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : List[str] = {'unk_token': '<unk>'} __a : Dict = os.path.join(self.tmpdirname , 'bart_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['vocab_file'] ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowerCAmelCase ( self : str ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) ) def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Tuple = os.path.join(self.tmpdirname , 'rag_tokenizer' ) __a : Optional[Any] = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) __a : Optional[Any] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Optional[Any] = RagTokenizer.from_pretrained('facebook/rag-token-nq' ) __a : List[Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Any = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' ) __a : Union[str, Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : str = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
47
0
def __UpperCAmelCase ( __a : str ) -> str: """simple docstring""" if not all(char in '''01''' for char in bin_string ): raise ValueError('''Non-binary value was passed to the function''' ) if not bin_string: raise ValueError('''Empty string was passed to the function''' ) _a : Union[str, Any] = '''''' while len(__a ) % 3 != 0: _a : Tuple = '''0''' + bin_string _a : int = [ bin_string[index : index + 3] for index in range(len(__a ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: _a : str = 0 for index, val in enumerate(__a ): oct_val += int(2 ** (2 - index) * int(__a ) ) oct_string += str(__a ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
14
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''spiece.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } SCREAMING_SNAKE_CASE__ = {'''bert_for_seq_generation''': 512} class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : int = ['''input_ids''', '''attention_mask'''] def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : Any="<unk>" , SCREAMING_SNAKE_CASE__ : int="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="<::::>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : int = vocab_file __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): '''simple docstring''' __a : Union[str, Any] = self.__dict__.copy() __a : Any = None return state def __setstate__( self : int , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' __a : str = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : str = {} __a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' __a : int = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Optional[Any] = [] __a : Optional[int] = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token __a : Dict = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Tuple = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
import copy import re class A : '''simple docstring''' A__ = '''hp''' A__ = {} A__ = None @classmethod def lowerCamelCase__ (cls : str , _UpperCAmelCase : Any , _UpperCAmelCase : List[str] ) -> Tuple: """simple docstring""" lowercase__ = prefix lowercase__ = defaults cls.build_naming_info() @staticmethod def lowerCamelCase__ (_UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int ) -> Tuple: """simple docstring""" if len(_UpperCAmelCase ) == 0: return "" lowercase__ = None if any(char.isdigit() for char in word ): raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_UpperCAmelCase ) + 1 ): lowercase__ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: lowercase__ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_UpperCAmelCase : Union[str, Any] ): lowercase__ = """""" while integer != 0: lowercase__ = chr(ord("""A""" ) + integer % 10 ) + s integer //= 10 return s lowercase__ = 0 while True: lowercase__ = word + """#""" + int_to_alphabetic(_UpperCAmelCase ) if sword in info["reverse_short_word"]: continue else: lowercase__ = sword break lowercase__ = short_word lowercase__ = word return short_word @staticmethod def lowerCamelCase__ (_UpperCAmelCase : Dict , _UpperCAmelCase : Optional[int] ) -> Union[str, Any]: """simple docstring""" lowercase__ = param_name.split("""_""" ) lowercase__ = [TrialShortNamer.shortname_for_word(_UpperCAmelCase , _UpperCAmelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name lowercase__ = ["""""", """_"""] for separator in separators: lowercase__ = separator.join(_UpperCAmelCase ) if shortname not in info["reverse_short_param"]: lowercase__ = shortname lowercase__ = param_name return shortname return param_name @staticmethod def lowerCamelCase__ (_UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" lowercase__ = TrialShortNamer.shortname_for_key(_UpperCAmelCase , _UpperCAmelCase ) lowercase__ = short_name lowercase__ = param_name @classmethod def lowerCamelCase__ (cls : Union[str, Any] ) -> Tuple: """simple docstring""" if cls.NAMING_INFO is not None: return lowercase__ = { """short_word""": {}, """reverse_short_word""": {}, """short_param""": {}, """reverse_short_param""": {}, } lowercase__ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_UpperCAmelCase , _UpperCAmelCase ) lowercase__ = info @classmethod def lowerCamelCase__ (cls : str , _UpperCAmelCase : Tuple ) -> List[str]: """simple docstring""" cls.build_naming_info() assert cls.PREFIX is not None lowercase__ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue lowercase__ = cls.NAMING_INFO["""short_param"""][k] if isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowercase__ = 1 if v else 0 lowercase__ = """""" if isinstance(_UpperCAmelCase , (int, float) ) else """-""" lowercase__ = f'''{key}{sep}{v}''' name.append(_UpperCAmelCase ) return "_".join(_UpperCAmelCase ) @classmethod def lowerCamelCase__ (cls : Union[str, Any] , _UpperCAmelCase : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ = repr[len(cls.PREFIX ) + 1 :] if repr == "": lowercase__ = [] else: lowercase__ = repr.split("""_""" ) lowercase__ = {} for value in values: if "-" in value: lowercase__ , lowercase__ = value.split("""-""" ) else: lowercase__ = re.sub("""[0-9.]""" , """""" , _UpperCAmelCase ) lowercase__ = float(re.sub("""[^0-9.]""" , """""" , _UpperCAmelCase ) ) lowercase__ = cls.NAMING_INFO["""reverse_short_param"""][p_k] lowercase__ = p_v for k in cls.DEFAULTS: if k not in parameters: lowercase__ = cls.DEFAULTS[k] return parameters
15
from ..utils import DummyObject, requires_backends class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Any = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Dict , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] )
47
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __A : Optional[Any] = '0.12' # assumed parallelism: 8 if is_torch_available(): import torch def __a ( A__ : Any , A__ : Tuple , A__ : str=None ): if rng is None: SCREAMING_SNAKE_CASE = random.Random() SCREAMING_SNAKE_CASE = 1 for dim in shape: total_dims *= dim SCREAMING_SNAKE_CASE = [] for _ in range(A__ ): values.append(rng.randint(0 , vocab_size - 1 ) ) SCREAMING_SNAKE_CASE = np.array(A__ , dtype=jnp.intaa ).reshape(A__ ) return output def __a ( A__ : Union[str, Any] , A__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE = ids_tensor(A__ , vocab_size=2 , rng=A__ ) # make sure that at least one token is attended to for each batch SCREAMING_SNAKE_CASE = 1 return attn_mask @require_flax class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowerCamelCase__ = None lowerCamelCase__ = () def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = inputs["input_ids"].shape[-1] // 2 SCREAMING_SNAKE_CASE = inputs["input_ids"][:max_batch_size, :sequence_length] SCREAMING_SNAKE_CASE = jnp.ones_like(__lowerCamelCase ) SCREAMING_SNAKE_CASE = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens SCREAMING_SNAKE_CASE = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` SCREAMING_SNAKE_CASE = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _snake_case ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 0 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE = pt_model_class(__lowerCamelCase ).eval() SCREAMING_SNAKE_CASE = load_flax_weights_in_pytorch_model(__lowerCamelCase , flax_model.params ) SCREAMING_SNAKE_CASE = flax_model.generate(__lowerCamelCase ).sequences SCREAMING_SNAKE_CASE = pt_model.generate(torch.tensor(__lowerCamelCase , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: SCREAMING_SNAKE_CASE = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 0.8 SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = 0.3 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 8 SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 8 SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 8 SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _snake_case ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , __lowerCamelCase ) SCREAMING_SNAKE_CASE = jit(model.generate ) SCREAMING_SNAKE_CASE = jit_generate(__lowerCamelCase , attention_mask=__lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" ) SCREAMING_SNAKE_CASE = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE = "Hello world" SCREAMING_SNAKE_CASE = tokenizer(__lowerCamelCase , return_tensors="np" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__lowerCamelCase , "do_samples" ): model.generate(__lowerCamelCase , do_samples=__lowerCamelCase ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__lowerCamelCase , "foo" ): SCREAMING_SNAKE_CASE = {"foo": "bar"} model.generate(__lowerCamelCase , **__lowerCamelCase )
16
import math from datetime import datetime, timedelta def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Union[str, Any] = year % 1_9 __a : int = year % 4 __a : Optional[int] = year % 7 __a : Dict = math.floor(year / 1_0_0 ) __a : Optional[Any] = math.floor((1_3 + 8 * leap_day_inhibits) / 2_5 ) __a : Union[str, Any] = leap_day_inhibits / 4 __a : str = ( 1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 3_0 __a : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __a : List[Any] = (1_9 * metonic_cycle + secular_moon_shift) % 3_0 # PHM -> Paschal Full Moon __a : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 2_9 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_9 ) elif days_to_add == 2_8 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_8 ) else: return datetime(lowerCamelCase_ , 3 , 2_2 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): SCREAMING_SNAKE_CASE__ = '''will be''' if year > datetime.now().year else '''was''' print(F"Easter in {year} {tense} {gauss_easter(year)}")
47
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase_ : Optional[Any] = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
17
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = '''informer''' __SCREAMING_SNAKE_CASE : List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "student_t" , SCREAMING_SNAKE_CASE__ : str = "nll" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : List[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : int = 6_4 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.05 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str = "prob" , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Dict = prediction_length __a : Tuple = context_length or prediction_length __a : Tuple = distribution_output __a : Tuple = loss __a : str = input_size __a : Dict = num_time_features __a : Optional[int] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __a : str = scaling __a : Tuple = num_dynamic_real_features __a : int = num_static_real_features __a : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __a : Optional[Any] = cardinality else: __a : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __a : int = embedding_dimension else: __a : List[Any] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] __a : int = num_parallel_samples # Transformer architecture configuration __a : str = input_size * len(self.lags_sequence ) + self._number_of_features __a : Optional[int] = d_model __a : Union[str, Any] = encoder_attention_heads __a : int = decoder_attention_heads __a : Any = encoder_ffn_dim __a : Union[str, Any] = decoder_ffn_dim __a : List[Any] = encoder_layers __a : Optional[int] = decoder_layers __a : int = dropout __a : Optional[Any] = attention_dropout __a : Dict = activation_dropout __a : Union[str, Any] = encoder_layerdrop __a : Optional[int] = decoder_layerdrop __a : List[str] = activation_function __a : str = init_std __a : Optional[int] = use_cache # Informer __a : Union[str, Any] = attention_type __a : str = sampling_factor __a : Dict = distil super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
0
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : List[Any] = "data2vec-audio" def __init__( self , _lowerCAmelCase=32 , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-5 , _lowerCAmelCase="gelu" , _lowerCAmelCase=(512, 512, 512, 512, 512, 512, 512) , _lowerCAmelCase=(5, 2, 2, 2, 2, 2, 2) , _lowerCAmelCase=(10, 3, 3, 3, 3, 2, 2) , _lowerCAmelCase=False , _lowerCAmelCase=16 , _lowerCAmelCase=19 , _lowerCAmelCase=5 , _lowerCAmelCase=0.05 , _lowerCAmelCase=10 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0 , _lowerCAmelCase=10 , _lowerCAmelCase=0 , _lowerCAmelCase="sum" , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=256 , _lowerCAmelCase=(512, 512, 512, 512, 1500) , _lowerCAmelCase=(5, 3, 3, 1, 1) , _lowerCAmelCase=(1, 2, 3, 1, 1) , _lowerCAmelCase=512 , _lowerCAmelCase=0 , _lowerCAmelCase=1 , _lowerCAmelCase=2 , _lowerCAmelCase=False , _lowerCAmelCase=3 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=None , **_lowerCAmelCase , ) -> Dict: super().__init__(**_lowerCAmelCase , pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase ) _lowerCAmelCase = hidden_size _lowerCAmelCase = feat_extract_activation _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = conv_bias _lowerCAmelCase = num_conv_pos_embeddings _lowerCAmelCase = num_conv_pos_embedding_groups _lowerCAmelCase = conv_pos_kernel_size _lowerCAmelCase = len(self.conv_dim ) _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_act _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = activation_dropout _lowerCAmelCase = feat_proj_dropout _lowerCAmelCase = final_dropout _lowerCAmelCase = layerdrop _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range _lowerCAmelCase = vocab_size _lowerCAmelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==" " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _lowerCAmelCase = mask_time_prob _lowerCAmelCase = mask_time_length _lowerCAmelCase = mask_time_min_masks _lowerCAmelCase = mask_feature_prob _lowerCAmelCase = mask_feature_length _lowerCAmelCase = mask_feature_min_masks # ctc loss _lowerCAmelCase = ctc_loss_reduction _lowerCAmelCase = ctc_zero_infinity # adapter _lowerCAmelCase = add_adapter _lowerCAmelCase = adapter_kernel_size _lowerCAmelCase = adapter_stride _lowerCAmelCase = num_adapter_layers _lowerCAmelCase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _lowerCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = list(_lowerCAmelCase ) _lowerCAmelCase = xvector_output_dim @property def _snake_case ( self ) -> str: return math.prod(self.conv_stride )
18
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE : Union[str, Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : List[str] = 1_0, 0.0 __a : Dict = self.dummy_model() __a : str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __a : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config(steps_offset=1 ) __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 1_0, 5_0] , [1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for t, eta in zip([1, 1_0, 4_9] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 , 4_0_0 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 , 9_6_0 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 , 4_8_6 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 , 9_9_8 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config() __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : Any = 1_0, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = self.dummy_model() __a : int = self.dummy_sample_deter __a : List[Any] = self.dummy_sample_deter + 0.1 __a : List[str] = self.dummy_sample_deter - 0.1 __a : Optional[Any] = samplea.shape[0] __a : Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) __a : Union[str, Any] = torch.arange(SCREAMING_SNAKE_CASE__ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE__ ) __a : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a : int = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE__ ) __a : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : List[str] = self.full_loop() __a : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : Dict = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
47
0
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _a = logging.get_logger(__name__) _a = { """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""", # See all DETR models at https://huggingface.co/models?filter=detr } class _UpperCAmelCase( lowerCamelCase ): lowercase__ = 'detr' lowercase__ = ['past_key_values'] lowercase__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , __a=True , __a=None , __a=3 , __a=1_00 , __a=6 , __a=20_48 , __a=8 , __a=6 , __a=20_48 , __a=8 , __a=0.0 , __a=0.0 , __a=True , __a="relu" , __a=2_56 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.02 , __a=1.0 , __a=False , __a="sine" , __a="resnet50" , __a=True , __a=False , __a=1 , __a=5 , __a=2 , __a=1 , __a=1 , __a=5 , __a=2 , __a=0.1 , **__a , ) -> int: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''') if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''') _UpperCamelCase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']) elif isinstance(__a , __a): _UpperCamelCase = backbone_config.get('''model_type''') _UpperCamelCase = CONFIG_MAPPING[backbone_model_type] _UpperCamelCase = config_class.from_dict(__a) # set timm attributes to None _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None, None, None _UpperCamelCase = use_timm_backbone _UpperCamelCase = backbone_config _UpperCamelCase = num_channels _UpperCamelCase = num_queries _UpperCamelCase = d_model _UpperCamelCase = encoder_ffn_dim _UpperCamelCase = encoder_layers _UpperCamelCase = encoder_attention_heads _UpperCamelCase = decoder_ffn_dim _UpperCamelCase = decoder_layers _UpperCamelCase = decoder_attention_heads _UpperCamelCase = dropout _UpperCamelCase = attention_dropout _UpperCamelCase = activation_dropout _UpperCamelCase = activation_function _UpperCamelCase = init_std _UpperCamelCase = init_xavier_std _UpperCamelCase = encoder_layerdrop _UpperCamelCase = decoder_layerdrop _UpperCamelCase = encoder_layers _UpperCamelCase = auxiliary_loss _UpperCamelCase = position_embedding_type _UpperCamelCase = backbone _UpperCamelCase = use_pretrained_backbone _UpperCamelCase = dilation # Hungarian matcher _UpperCamelCase = class_cost _UpperCamelCase = bbox_cost _UpperCamelCase = giou_cost # Loss coefficients _UpperCamelCase = mask_loss_coefficient _UpperCamelCase = dice_loss_coefficient _UpperCamelCase = bbox_loss_coefficient _UpperCamelCase = giou_loss_coefficient _UpperCamelCase = eos_coefficient super().__init__(is_encoder_decoder=__a , **__a) @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return self.encoder_attention_heads @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return self.d_model @classmethod def UpperCAmelCase ( cls , __a , **__a) -> int: '''simple docstring''' return cls(backbone_config=__a , **__a) def UpperCAmelCase ( self) -> Dict[str, any]: '''simple docstring''' _UpperCamelCase = copy.deepcopy(self.__dict__) if output["backbone_config"] is not None: _UpperCamelCase = self.backbone_config.to_dict() _UpperCamelCase = self.__class__.model_type return output class _UpperCAmelCase( lowerCamelCase ): lowercase__ = version.parse('1.11' ) @property def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ]) @property def UpperCAmelCase ( self) -> float: '''simple docstring''' return 1e-5 @property def UpperCAmelCase ( self) -> int: '''simple docstring''' return 12
19
def UpperCAmelCase__ ( lowerCamelCase_ : list[int] , lowerCamelCase_ : list[int] ): # Check if the input is valid if not len(lowerCamelCase_ ) == len(lowerCamelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __a , __a , __a : Optional[Any] = equationa __a , __a , __a : Optional[int] = equationa # Calculate the determinants of the matrices __a : str = aa * ba - aa * ba __a : Tuple = ca * ba - ca * ba __a : Union[str, Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __a : Any = determinant_x / determinant __a : Optional[Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
47
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase_ (lowercase__ ): snake_case =['image_processor', 'tokenizer'] snake_case ='ViltImageProcessor' snake_case =('BertTokenizer', 'BertTokenizerFast') def __init__( self , lowercase_=None , lowercase_=None , **lowercase_) -> Optional[Any]: a__ =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , lowercase_ , ) a__ =kwargs.pop('feature_extractor') a__ =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(lowercase_ , lowercase_) a__ =self.image_processor def __call__( self , lowercase_ , lowercase_ = None , lowercase_ = True , lowercase_ = False , lowercase_ = None , lowercase_ = None , lowercase_ = 0 , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = False , lowercase_ = False , lowercase_ = False , lowercase_ = False , lowercase_ = True , lowercase_ = None , **lowercase_ , ) -> BatchEncoding: a__ =self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_token_type_ids=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) # add pixel_values + pixel_mask a__ =self.image_processor(lowercase_ , return_tensors=lowercase_) encoding.update(lowercase_) return encoding def __UpperCamelCase ( self , *lowercase_ , **lowercase_) -> int: return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def __UpperCamelCase ( self , *lowercase_ , **lowercase_) -> Tuple: return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def __UpperCamelCase ( self) -> Optional[Any]: a__ =self.tokenizer.model_input_names a__ =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def __UpperCamelCase ( self) -> List[str]: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , lowercase_ , ) return self.image_processor_class @property def __UpperCamelCase ( self) -> Union[str, Any]: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , lowercase_ , ) return self.image_processor
20
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
47
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record UpperCAmelCase_ : int = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" UpperCAmelCase_ : Any = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" UpperCAmelCase_ : Tuple = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ): return float((preds == labels).mean() ) def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase="binary" ): __magic_name__ : Optional[int] =simple_accuracy(lowerCamelCase , lowerCamelCase ) __magic_name__ : Optional[int] =float(fa_score(y_true=lowerCamelCase , y_pred=lowerCamelCase , average=lowerCamelCase ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ): __magic_name__ : Tuple ={} for id_pred, label in zip(lowerCamelCase , lowerCamelCase ): __magic_name__ : List[Any] =F"{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}" __magic_name__ : Any =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: __magic_name__ : Optional[int] =[(pred, label)] __magic_name__ , __magic_name__ : Dict =[], [] for question, preds_labels in question_map.items(): __magic_name__ , __magic_name__ : Tuple =zip(*lowerCamelCase ) __magic_name__ : str =fa_score(y_true=lowerCamelCase , y_pred=lowerCamelCase , average="""macro""" ) fas.append(lowerCamelCase ) __magic_name__ : Optional[int] =int(sum(pred == label for pred, label in preds_labels ) == len(lowerCamelCase ) ) ems.append(lowerCamelCase ) __magic_name__ : Any =float(sum(lowerCamelCase ) / len(lowerCamelCase ) ) __magic_name__ : str =sum(lowerCamelCase ) / len(lowerCamelCase ) __magic_name__ : Any =float(fa_score(y_true=lowerCamelCase , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def A__ ( self :str ): '''simple docstring''' if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def A__ ( self :int ): '''simple docstring''' if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def A__ ( self :Union[str, Any] , __snake_case :List[str] , __snake_case :List[Any] ): '''simple docstring''' if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__snake_case , __snake_case )} elif self.config_name == "cb": return acc_and_fa(__snake_case , __snake_case , fa_avg="""macro""" ) elif self.config_name == "record": __magic_name__ : List[str] =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] __magic_name__ : Optional[int] ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__snake_case , __snake_case )[0] elif self.config_name == "multirc": return evaluate_multirc(__snake_case , __snake_case ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__snake_case , __snake_case )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
21
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
47
0
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def snake_case_ (UpperCamelCase : dict ): '''simple docstring''' return (data["data"], data["target"]) def snake_case_ (UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray ): '''simple docstring''' _a = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(UpperCamelCase , UpperCamelCase ) # Predict target for test data _a = xgb.predict(UpperCamelCase ) _a = predictions.reshape(len(UpperCamelCase ) , 1 ) return predictions def snake_case_ (): '''simple docstring''' _a = fetch_california_housing() _a , _a = data_handling(UpperCamelCase ) _a , _a , _a , _a = train_test_split( UpperCamelCase , UpperCamelCase , test_size=0.25 , random_state=1 ) _a = xgboost(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # Error printing print(f'Mean Absolute Error : {mean_absolute_error(UpperCamelCase , UpperCamelCase )}' ) print(f'Mean Square Error : {mean_squared_error(UpperCamelCase , UpperCamelCase )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
22
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
0
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py snake_case__ : int = """src/transformers""" snake_case__ : Dict = """docs/source/en/tasks""" def _snake_case (__lowercase , __lowercase , __lowercase): with open(__lowercase , 'r' , encoding='utf-8' , newline='\n') as f: UpperCamelCase_ = f.readlines() # Find the start prompt. UpperCamelCase_ = 0 while not lines[start_index].startswith(__lowercase): start_index += 1 start_index += 1 UpperCamelCase_ = start_index while not lines[end_index].startswith(__lowercase): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. snake_case__ : int = direct_transformers_import(TRANSFORMERS_PATH) snake_case__ : Any = { """asr.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, """audio_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, """language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, """image_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, """masked_language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, """multiple_choice.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, """object_detection.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, """question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, """semantic_segmentation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, """sequence_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, """summarization.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """token_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, """translation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """video_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, """document_question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, """monocular_depth_estimation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). snake_case__ : Any = { """summarization.md""": ("""nllb""",), """translation.md""": ("""nllb""",), } def _snake_case (__lowercase): UpperCamelCase_ = TASK_GUIDE_TO_MODELS[task_guide] UpperCamelCase_ = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(__lowercase , set()) UpperCamelCase_ = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f"""[{name}](../model_doc/{code})""" for code, name in model_names.items()]) + "\n" def _snake_case (__lowercase , __lowercase=False): UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = _find_text_in_file( filename=os.path.join(__lowercase , __lowercase) , start_prompt='<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->' , end_prompt='<!--End of the generated tip-->' , ) UpperCamelCase_ = get_model_list_for_task(__lowercase) if current_list != new_list: if overwrite: with open(os.path.join(__lowercase , __lowercase) , 'w' , encoding='utf-8' , newline='\n') as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:]) else: raise ValueError( f"""The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`""" ' to fix this.') if __name__ == "__main__": snake_case__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") snake_case__ : str = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
23
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''sew-d''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=("p2c", "c2p") , SCREAMING_SNAKE_CASE__ : str="layer_norm" , SCREAMING_SNAKE_CASE__ : Tuple="gelu_python" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-7 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Optional[int]="group" , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : str=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2_8 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]="mean" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=2_5_6 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = hidden_size __a : Optional[Any] = feat_extract_norm __a : List[str] = feat_extract_activation __a : Dict = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = list(SCREAMING_SNAKE_CASE__ ) __a : List[str] = list(SCREAMING_SNAKE_CASE__ ) __a : int = conv_bias __a : Tuple = num_conv_pos_embeddings __a : List[str] = num_conv_pos_embedding_groups __a : Optional[Any] = len(self.conv_dim ) __a : Union[str, Any] = num_hidden_layers __a : Optional[Any] = intermediate_size __a : Union[str, Any] = squeeze_factor __a : List[Any] = max_position_embeddings __a : Tuple = position_buckets __a : Optional[int] = share_att_key __a : List[str] = relative_attention __a : Any = norm_rel_ebd __a : Any = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = hidden_act __a : str = num_attention_heads __a : Union[str, Any] = hidden_dropout __a : Optional[int] = attention_dropout __a : List[str] = activation_dropout __a : int = feat_proj_dropout __a : int = final_dropout __a : Dict = layer_norm_eps __a : Tuple = feature_layer_norm_eps __a : str = initializer_range __a : Tuple = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : Tuple = apply_spec_augment __a : Optional[Any] = mask_time_prob __a : Any = mask_time_length __a : List[str] = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Tuple = mask_feature_length __a : Any = mask_feature_min_masks # ctc loss __a : Optional[int] = ctc_loss_reduction __a : List[Any] = ctc_zero_infinity # sequence classification __a : Dict = use_weighted_layer_sum __a : Optional[Any] = classifier_proj_size @property def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
47
0
'''simple docstring''' 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 : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=13 , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=99 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=37 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=512 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=None , ) -> Optional[int]: '''simple docstring''' __snake_case = parent __snake_case = 13 __snake_case = 7 __snake_case = True __snake_case = True __snake_case = True __snake_case = True __snake_case = 99 __snake_case = 384 __snake_case = 2 __snake_case = 4 __snake_case = 37 __snake_case = '''gelu''' __snake_case = 0.1 __snake_case = 0.1 __snake_case = 512 __snake_case = 16 __snake_case = 2 __snake_case = 0.02 __snake_case = 3 __snake_case = 4 __snake_case = 128 __snake_case = 2 __snake_case = 9 __snake_case = 1 __snake_case = None def lowerCAmelCase ( self ) -> Tuple: '''simple docstring''' __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case = None if self.use_input_mask: __snake_case = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case = None if self.use_token_type_ids: __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case = None __snake_case = None __snake_case = None if self.use_labels: __snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case = ids_tensor([self.batch_size] , self.num_choices ) __snake_case = 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=__SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' __snake_case = TFConvBertModel(config=__SCREAMING_SNAKE_CASE ) __snake_case = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __snake_case = [input_ids, input_mask] __snake_case = model(__SCREAMING_SNAKE_CASE ) __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' __snake_case = TFConvBertForMaskedLM(config=__SCREAMING_SNAKE_CASE ) __snake_case = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' __snake_case = self.num_labels __snake_case = TFConvBertForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) __snake_case = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' __snake_case = self.num_choices __snake_case = TFConvBertForMultipleChoice(config=__SCREAMING_SNAKE_CASE ) __snake_case = tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __snake_case = tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __snake_case = tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __snake_case = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' __snake_case = self.num_labels __snake_case = TFConvBertForTokenClassification(config=__SCREAMING_SNAKE_CASE ) __snake_case = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' __snake_case = TFConvBertForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) __snake_case = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __snake_case = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' __snake_case = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) = config_and_inputs __snake_case = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase): __lowercase : str = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __lowercase : Optional[int] = ( { '''feature-extraction''': TFConvBertModel, '''fill-mask''': TFConvBertForMaskedLM, '''question-answering''': TFConvBertForQuestionAnswering, '''text-classification''': TFConvBertForSequenceClassification, '''token-classification''': TFConvBertForTokenClassification, '''zero-shot''': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __lowercase : Optional[Any] = False __lowercase : List[str] = False __lowercase : Union[str, Any] = False def lowerCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' __snake_case = TFConvBertModelTester(self ) __snake_case = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def lowerCAmelCase ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> List[str]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> List[Any]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Any: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Any: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) @slow def lowerCAmelCase ( self ) -> List[Any]: '''simple docstring''' __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() __snake_case = True __snake_case = True if hasattr(__SCREAMING_SNAKE_CASE , '''use_cache''' ): __snake_case = True __snake_case = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __snake_case = getattr(self.model_tester , '''key_length''' , __SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __snake_case = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __snake_case = model_class(__SCREAMING_SNAKE_CASE ) __snake_case = len(model(__SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__SCREAMING_SNAKE_CASE , saved_model=__SCREAMING_SNAKE_CASE ) __snake_case = os.path.join(__SCREAMING_SNAKE_CASE , '''saved_model''' , '''1''' ) __snake_case = tf.keras.models.load_model(__SCREAMING_SNAKE_CASE ) __snake_case = model(__SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __snake_case = outputs['''encoder_hidden_states'''] __snake_case = outputs['''encoder_attentions'''] else: __snake_case = outputs['''hidden_states'''] __snake_case = outputs['''attentions'''] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __snake_case = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 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 lowerCAmelCase ( self ) -> Optional[int]: '''simple docstring''' __snake_case = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Optional[int]: '''simple docstring''' __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() __snake_case = True __snake_case = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length ) __snake_case = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __snake_case = getattr(self.model_tester , '''key_length''' , __SCREAMING_SNAKE_CASE ) __snake_case = getattr(self.model_tester , '''key_length''' , __SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(__SCREAMING_SNAKE_CASE ): __snake_case = len(__SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __snake_case = outputs.decoder_attentions self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 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(__SCREAMING_SNAKE_CASE ): __snake_case = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 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: __snake_case = True __snake_case = False __snake_case = model_class(__SCREAMING_SNAKE_CASE ) __snake_case = model(self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __snake_case = len(__SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , __SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(__SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __snake_case = model_class(__SCREAMING_SNAKE_CASE ) __snake_case = model(self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , __SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(__SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __snake_case = True __snake_case = model_class(__SCREAMING_SNAKE_CASE ) __snake_case = model(self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , __SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(__SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __snake_case = True __snake_case = True __snake_case = model_class(__SCREAMING_SNAKE_CASE ) __snake_case = model(self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , __SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(__SCREAMING_SNAKE_CASE ) @require_tf class lowerCAmelCase ( unittest.TestCase): @slow def lowerCAmelCase ( self ) -> Any: '''simple docstring''' __snake_case = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) __snake_case = tf.constant([[0, 1, 2, 3, 4, 5]] ) __snake_case = model(__SCREAMING_SNAKE_CASE )[0] __snake_case = [1, 6, 768] self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) __snake_case = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 )
24
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Any = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token")) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings")) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight")) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias")) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight")) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight")) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias")) for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias")) # transformer encoder for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight")) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias")) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight")) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias")) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight")) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias")) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight")) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias")) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight")) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias")) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ]) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE : List[str] = [(pair[0], pair[1][4:]) if pair[1].startswith("vit") else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ]) # fmt: on return rename_keys def lowerCamelCase__ ( _a , _a , _a=False): for i in range(config.num_hidden_layers): if base_model: SCREAMING_SNAKE_CASE : Any = "" else: SCREAMING_SNAKE_CASE : Optional[int] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(f"blocks.{i}.attn.qkv.weight") SCREAMING_SNAKE_CASE : List[Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : str = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE : Any = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE : str = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE : Any = in_proj_bias[-config.hidden_size :] def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Union[str, Any] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_a , _a) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : Any = dct.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[int] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Tuple = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a , _a=False): SCREAMING_SNAKE_CASE : Any = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=_a , ) SCREAMING_SNAKE_CASE : Tuple = ViTHybridConfig(backbone_config=_a , image_size=384 , num_labels=1000) SCREAMING_SNAKE_CASE : Any = False # load original model from timm SCREAMING_SNAKE_CASE : Any = timm.create_model(_a , pretrained=_a) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE : Any = timm_model.state_dict() if base_model: remove_classification_head_(_a) SCREAMING_SNAKE_CASE : Dict = create_rename_keys(_a , _a) for src, dest in rename_keys: rename_key(_a , _a , _a) read_in_q_k_v(_a , _a , _a) SCREAMING_SNAKE_CASE : List[str] = "huggingface/label-files" SCREAMING_SNAKE_CASE : List[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : List[Any] = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[str] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE : Dict = ViTHybridModel(_a).eval() else: SCREAMING_SNAKE_CASE : Dict = ViTHybridForImageClassification(_a).eval() model.load_state_dict(_a) # create image processor SCREAMING_SNAKE_CASE : int = create_transform(**resolve_data_config({} , model=_a)) SCREAMING_SNAKE_CASE : Tuple = transform.transforms SCREAMING_SNAKE_CASE : Optional[int] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : List[str] = ViTHybridImageProcessor( do_resize=_a , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_a , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_a , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : List[Any] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = transform(_a).unsqueeze(0) SCREAMING_SNAKE_CASE : str = processor(_a , return_tensors="pt").pixel_values # verify pixel values assert torch.allclose(_a , _a) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : int = model(_a) SCREAMING_SNAKE_CASE : int = outputs.logits print("Predicted class:" , logits.argmax(-1).item()) if base_model: SCREAMING_SNAKE_CASE : List[Any] = timm_model.forward_features(_a) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_a , outputs.pooler_output , atol=1E-3) else: SCREAMING_SNAKE_CASE : Union[str, Any] = timm_model(_a) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_a , outputs.logits , atol=1E-3) print("Looks ok!") if pytorch_dump_folder_path is not None: Path(_a).mkdir(exist_ok=_a) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}") model.save_pretrained(_a) print(f"Saving processor to {pytorch_dump_folder_path}") processor.save_pretrained(_a) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}") model.push_to_hub(f"ybelkada/{vit_name}") processor.push_to_hub(f"ybelkada/{vit_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) a_ = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
25
from collections.abc import Sequence from queue import Queue class _UpperCamelCase: def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None ): '''simple docstring''' __a : Tuple = start __a : Dict = end __a : List[str] = val __a : List[Any] = (start + end) // 2 __a : Optional[Any] = left __a : List[str] = right def __repr__( self : Dict ): '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class _UpperCamelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Sequence , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Tuple = collection __a : Dict = function if self.collection: __a : int = self._build_tree(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.collection[start] ) __a : Tuple = (start + end) // 2 __a : Optional[int] = self._build_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Tuple = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE__ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if node.start == i and node.end == i: __a : Optional[Any] = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = self.fn(node.left.val , node.right.val ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE__ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE__ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' if self.root is not None: __a : Tuple = Queue() queue.put(self.root ) while not queue.empty(): __a : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) SCREAMING_SNAKE_CASE__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
47
0
'''simple docstring''' from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging __UpperCamelCase = logging.get_logger(__name__) class _A : lowercase__: str lowercase__: str = None @staticmethod def lowercase__ ( ) -> Dict: """simple docstring""" raise NotImplementedError def lowercase__ ( self : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : str , **__magic_name__ : Union[str, Any] ) -> Tuple: """simple docstring""" raise NotImplementedError def lowercase__ ( self : int , __magic_name__ : Optional[Any] ) -> Any: """simple docstring""" raise NotImplementedError def lowercase__ ( self : str ) -> List[str]: """simple docstring""" if not self.is_available(): raise RuntimeError( f'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowercase__ ( cls : Optional[Any] ) -> int: """simple docstring""" return f'''`pip install {cls.pip_package or cls.name}`''' class _A ( __lowercase ): lowercase__: str = '''optuna''' @staticmethod def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" return is_optuna_available() def lowercase__ ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : str , **__magic_name__ : List[Any] ) -> Optional[Any]: """simple docstring""" return run_hp_search_optuna(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowercase__ ( self : Dict , __magic_name__ : Tuple ) -> Optional[int]: """simple docstring""" return default_hp_space_optuna(__magic_name__ ) class _A ( __lowercase ): lowercase__: Dict = '''ray''' lowercase__: Optional[Any] = '''\'ray[tune]\'''' @staticmethod def lowercase__ ( ) -> str: """simple docstring""" return is_ray_available() def lowercase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : str , **__magic_name__ : List[str] ) -> Union[str, Any]: """simple docstring""" return run_hp_search_ray(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowercase__ ( self : Dict , __magic_name__ : Dict ) -> Optional[int]: """simple docstring""" return default_hp_space_ray(__magic_name__ ) class _A ( __lowercase ): lowercase__: str = '''sigopt''' @staticmethod def lowercase__ ( ) -> List[Any]: """simple docstring""" return is_sigopt_available() def lowercase__ ( self : str , __magic_name__ : str , __magic_name__ : int , __magic_name__ : str , **__magic_name__ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" return run_hp_search_sigopt(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowercase__ ( self : List[str] , __magic_name__ : Dict ) -> int: """simple docstring""" return default_hp_space_sigopt(__magic_name__ ) class _A ( __lowercase ): lowercase__: Optional[int] = '''wandb''' @staticmethod def lowercase__ ( ) -> List[str]: """simple docstring""" return is_wandb_available() def lowercase__ ( self : Dict , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , **__magic_name__ : Any ) -> int: """simple docstring""" return run_hp_search_wandb(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowercase__ ( self : Dict , __magic_name__ : Tuple ) -> Optional[int]: """simple docstring""" return default_hp_space_wandb(__magic_name__ ) __UpperCamelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def _a ( ) -> str: """simple docstring""" __snake_case : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_lowerCamelCase ) > 0: __snake_case : Union[str, Any] = available_backends[0].name if len(_lowerCamelCase ) > 1: logger.info( F'''{len(_lowerCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
26
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int SCREAMING_SNAKE_CASE__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _UpperCamelCase( datasets.BuilderConfig ): __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None def UpperCAmelCase__ ( lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[int] , ): import pyspark def generate_fn(): __a : List[Any] = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __a : Optional[int] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __a : Optional[Any] = partition_df.collect() __a : Union[str, Any] = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _UpperCamelCase( _BaseExamplesIterable ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : Dict=None , ): '''simple docstring''' __a : List[str] = df __a : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) __a : List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.random.Generator ): '''simple docstring''' __a : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return len(self.partition_order ) class _UpperCamelCase( datasets.DatasetBuilder ): __SCREAMING_SNAKE_CASE : List[str] = SparkConfig def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' import pyspark __a : int = pyspark.sql.SparkSession.builder.getOrCreate() __a : Optional[int] = df __a : List[Any] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__ : List[str] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE__ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __a : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE__ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE__ : int ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __a : List[str] = self.df.count() __a : Dict = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __a : List[str] = ( self.df.limit(SCREAMING_SNAKE_CASE__ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE__ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __a : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __a : Union[str, Any] = min(SCREAMING_SNAKE_CASE__ , int(approx_total_size / max_shard_size ) ) __a : int = self.df.repartition(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , ): '''simple docstring''' import pyspark __a : Any = ParquetWriter if file_format == 'parquet' else ArrowWriter __a : Union[str, Any] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) if self._working_dir else fpath __a : Optional[int] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __a : List[str] = self.config.features __a : int = self._writer_batch_size __a : Union[str, Any] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __a : Any = pyspark.TaskContext().taskAttemptId() __a : str = next(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __a : Any = 0 __a : List[str] = writer_class( features=SCREAMING_SNAKE_CASE__ , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __a , __a : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __a : Optional[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Union[str, Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) if writer._num_bytes > 0: __a , __a : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ): __a : Any = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ) , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) shutil.move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE__ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , SCREAMING_SNAKE_CASE__ : str = "arrow" , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' self._validate_cache_dir() __a : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = not is_remote_filesystem(self._fs ) __a : Optional[Any] = os.path.join if is_local else posixpath.join __a : Any = '-TTTTT-SSSSS-of-NNNNN' __a : Union[str, Any] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __a : Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE__ ) __a : Any = 0 __a : Dict = 0 __a : int = 0 __a : List[str] = [] __a : Optional[int] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE__ ) __a : List[str] = total_num_examples __a : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __a : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __a : Dict = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): rename( SCREAMING_SNAKE_CASE__ , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __a : Union[str, Any] = [] __a : List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a , __a : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE__ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ).map(lambda SCREAMING_SNAKE_CASE__ : _rename_shard(*SCREAMING_SNAKE_CASE__ ) ).collect() else: # don't use any pattern __a : List[Any] = 0 __a : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE__ , '' ) , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
47
0
from __future__ import annotations class lowerCamelCase: '''simple docstring''' def __init__( self , snake_case_=None ): _A = data _A = None def __repr__( self ): _A = [] _A = self while temp: string_rep.append(F"{temp.data}" ) _A = temp.next return "->".join(snake_case_ ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" if not elements_list: raise Exception('The Elements List is empty' ) _A = _A = Node(elements_list[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): _A = Node(elements_list[i] ) _A = current.next return head def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if head_node is not None and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): print_reverse(head_node.next ) print(head_node.data ) def __lowerCAmelCase( ) -> Any: """simple docstring""" from doctest import testmod testmod() _A = make_linked_list([14, 52, 14, 12, 43] ) print('Linked List:' ) print(_SCREAMING_SNAKE_CASE ) print('Elements in Reverse:' ) print_reverse(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
27
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : int ): # save results if os.path.exists(lowerCamelCase_ ): if os.path.exists(os.path.join(lowerCamelCase_ , 'config.json' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'config.json' ) ): os.remove(os.path.join(lowerCamelCase_ , 'config.json' ) ) if os.path.exists(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ): os.remove(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) else: os.makedirs(lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : Any=False ): __a : Dict = 2 if unlogit: __a : Optional[Any] = torch.pow(lowerCamelCase_ , lowerCamelCase_ ) __a : Any = p * torch.log(lowerCamelCase_ ) __a : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ ( lowerCamelCase_ : Any ): logger.info('lv, h >\t' + '\t'.join(f'''{x + 1}''' for x in range(len(lowerCamelCase_ ) ) ) ) for row in range(len(lowerCamelCase_ ) ): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:d}''' for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=False ): __a , __a : Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads __a : str = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) __a : int = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) if head_mask is None: __a : Union[str, Any] = torch.ones(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCamelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __a : Any = None __a : Optional[int] = 0.0 __a : Optional[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCamelCase_ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __a : Dict = tuple(t.to(args.device ) for t in inputs ) ((__a) , ) : Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __a : List[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ , head_mask=lowerCamelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __a , __a , __a : int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCamelCase_ ): __a : List[str] = entropy(attn.detach() , lowerCamelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCamelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __a : Optional[Any] = 2 __a : Union[str, Any] = torch.pow(torch.pow(lowerCamelCase_ , lowerCamelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: __a : List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(lowerCamelCase_ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(lowerCamelCase_ ) logger.info('Head ranked by importance scores' ) __a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __a : str = torch.arange( head_importance.numel() , device=args.device ) __a : Tuple = head_ranks.view_as(lowerCamelCase_ ) print_ad_tensor(lowerCamelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): __a , __a , __a : Optional[int] = compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ ) __a : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , lowerCamelCase_ , original_score * args.masking_threshold ) __a : Tuple = torch.ones_like(lowerCamelCase_ ) __a : int = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __a : Tuple = original_score while current_score >= original_score * args.masking_threshold: __a : Optional[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __a : List[str] = float('Inf' ) __a : List[Any] = head_importance.view(-1 ).sort()[1] if len(lowerCamelCase_ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __a : Any = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __a : int = new_head_mask.view(-1 ) __a : Tuple = 0.0 __a : int = new_head_mask.view_as(lowerCamelCase_ ) __a : Optional[int] = new_head_mask.clone().detach() print_ad_tensor(lowerCamelCase_ ) # Compute metric and head importance again __a , __a , __a : int = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[Any] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowerCamelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(lowerCamelCase_ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): __a : List[Any] = datetime.now() __a , __a , __a : List[str] = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[str] = 1 / loss __a : List[Any] = datetime.now() - before_time __a : List[str] = sum(p.numel() for p in model.parameters() ) __a : Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __a : Tuple = [ v, ] assert sum(len(lowerCamelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCamelCase_ ) __a : Optional[Any] = sum(p.numel() for p in model.parameters() ) __a : Tuple = datetime.now() __a , __a , __a : Tuple = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ , actually_pruned=lowerCamelCase_ , ) __a : Optional[Any] = 1 / loss __a : List[Any] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowerCamelCase_ , lowerCamelCase_ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , lowerCamelCase_ , lowerCamelCase_ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(lowerCamelCase_ , args.output_dir ) def UpperCAmelCase__ ( ): __a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=lowerCamelCase_ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=lowerCamelCase_ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=lowerCamelCase_ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=lowerCamelCase_ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=lowerCamelCase_ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=lowerCamelCase_ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=lowerCamelCase_ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=lowerCamelCase_ , help='Batch size.' ) parser.add_argument('--seed' , type=lowerCamelCase_ , default=4_2 ) parser.add_argument('--local_rank' , type=lowerCamelCase_ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) __a : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCamelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __a : List[str] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __a : Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __a : Union[str, Any] = torch.device('cuda' , args.local_rank ) __a : Any = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __a : Optional[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __a : List[Any] = nn.parallel.DistributedDataParallel( lowerCamelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCamelCase_ ) elif args.n_gpu > 1: __a : Union[str, Any] = nn.DataParallel(lowerCamelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , lowerCamelCase_ ) # Prepare dataset __a : Tuple = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __a : str = (torch.from_numpy(lowerCamelCase_ ),) __a : List[str] = TensorDataset(*lowerCamelCase_ ) __a : Optional[Any] = RandomSampler(lowerCamelCase_ ) __a : Union[str, Any] = DataLoader(lowerCamelCase_ , sampler=lowerCamelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __a : Union[str, Any] = mask_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) prune_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
47
0
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = 1 # (0 is vertical, 1 is horizontal) def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = get_dataset(__UpperCamelCase ,__UpperCamelCase ) print('Processing...' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = update_image_and_anno(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) for index, image in enumerate(__UpperCamelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Tuple = random_chars(32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = paths[index].split(os.sep )[-1].rsplit('.' ,1 )[0] SCREAMING_SNAKE_CASE : Optional[int] = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cva.imwrite(f"/{file_root}.jpg" ,__UpperCamelCase ,[cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"Success {index+1}/{len(__UpperCamelCase )} with {file_name}" ) SCREAMING_SNAKE_CASE : Union[str, Any] = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE : Optional[Any] = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(__UpperCamelCase ) with open(f"/{file_root}.txt" ,'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def lowercase__( __UpperCamelCase: str ,__UpperCamelCase: str ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Optional[int] = [] for label_file in glob.glob(os.path.join(__UpperCamelCase ,'*.txt' ) ): SCREAMING_SNAKE_CASE : Optional[Any] = label_file.split(os.sep )[-1].rsplit('.' ,1 )[0] with open(__UpperCamelCase ) as in_file: SCREAMING_SNAKE_CASE : List[Any] = in_file.readlines() SCREAMING_SNAKE_CASE : Dict = os.path.join(__UpperCamelCase ,f"{label_name}.jpg" ) SCREAMING_SNAKE_CASE : str = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : str = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__UpperCamelCase ) labels.append(__UpperCamelCase ) return img_paths, labels def lowercase__( __UpperCamelCase: list ,__UpperCamelCase: list ,__UpperCamelCase: int = 1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : Any = [] for idx in range(len(__UpperCamelCase ) ): SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Tuple = img_list[idx] path_list.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE : str = anno_list[idx] SCREAMING_SNAKE_CASE : List[str] = cva.imread(__UpperCamelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE : Union[str, Any] = cva.flip(__UpperCamelCase ,__UpperCamelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE : Optional[Any] = cva.flip(__UpperCamelCase ,__UpperCamelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE : int = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__UpperCamelCase ) new_imgs_list.append(__UpperCamelCase ) return new_imgs_list, new_annos_lists, path_list def lowercase__( __UpperCamelCase: int = 32 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : Optional[Any] = ascii_lowercase + digits return "".join(random.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
28
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __a : List[Any] = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1_0_2_4, 'hidden_size': 7_6_8, 'max_length': 5_1_2, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1_0_2_4, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __a : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a : List[str] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a : int = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __a : Optional[Any] = os.path.join(get_home_dir() , 'models' ) __a : Optional[Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __a : Any = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __a : Dict = original_bort._collect_params_with_prefix() # Build our config 🤗 __a : Optional[Any] = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(lowerCamelCase_ ), } __a : str = BertConfig.from_dict(lowerCamelCase_ ) __a : Optional[int] = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Optional[Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __a : Optional[int] = hf_param.shape __a : int = to_torch(params[gluon_param] ) __a : int = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __a : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __a : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __a : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __a : BertSelfAttention = layer.attention.self __a : Optional[int] = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a : str = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a : str = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a : Dict = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a : str = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a : BertSelfOutput = layer.attention.output __a : Tuple = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a : Dict = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a : BertIntermediate = layer.intermediate __a : List[str] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a : Optional[Any] = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a : BertOutput = layer.output __a : str = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a : List[Any] = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a : List[str] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a : Union[str, Any] = RobertaTokenizer.from_pretrained('roberta-base' ) __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ )['input_ids'] # Get gluon output __a : Optional[int] = mx.nd.array([input_ids] ) __a : Tuple = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __a : Optional[Any] = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ , return_tensors='pt' ) __a : int = hf_bort_model(**lowerCamelCase_ )[0] __a : Dict = output_gluon[0].asnumpy() __a : str = output_hf[0].detach().numpy() __a : List[Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a : str = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
47
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ): return int((input_a, input_a).count(0 ) == 0 ) def lowercase ( ): assert and_gate(0 ,0 ) == 0 assert and_gate(0 ,1 ) == 0 assert and_gate(1 ,0 ) == 0 assert and_gate(1 ,1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
29
def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ): __a : Any = '' for i in table: res += inp[i - 1] return res def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] ): return data[1:] + data[0] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): __a : Optional[int] = '' for i in range(len(lowerCamelCase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): __a : List[str] = int('0b' + data[0] + data[-1] , 2 ) __a : List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = message[:4] __a : str = message[4:] __a : Any = apply_table(lowerCamelCase_ , lowerCamelCase_ ) __a : int = xor(lowerCamelCase_ , lowerCamelCase_ ) __a : Dict = apply_sbox(lowerCamelCase_ , temp[:4] ) # noqa: E741 __a : Tuple = apply_sbox(lowerCamelCase_ , temp[4:] ) __a : List[Any] = '0' * (2 - len(lowerCamelCase_ )) + l # noqa: E741 __a : List[str] = '0' * (2 - len(lowerCamelCase_ )) + r __a : List[Any] = apply_table(l + r , lowerCamelCase_ ) __a : Dict = xor(lowerCamelCase_ , lowerCamelCase_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE__ = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE__ = [6, 3, 7, 4, 8, 5, 10, 9] SCREAMING_SNAKE_CASE__ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] SCREAMING_SNAKE_CASE__ = [2, 4, 3, 1] SCREAMING_SNAKE_CASE__ = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE__ = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE__ = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE__ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE__ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE__ = apply_table(key, paa_table) SCREAMING_SNAKE_CASE__ = temp[:5] SCREAMING_SNAKE_CASE__ = temp[5:] SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE__ = apply_table(message, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE__ = apply_table(CT, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
47
0
import math import random def lowerCamelCase__ ( _lowercase , _lowercase = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __a = 0.02 def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' UpperCAmelCase_ : List[Any] = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(_lowercase ): # Forward propagation UpperCAmelCase_ : List[str] = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? UpperCAmelCase_ : Tuple = (expected / 100) - layer_a # Error delta UpperCAmelCase_ : int = layer_1_error * sigmoid_function(_lowercase , _lowercase ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __a = int(input('Expected value: ')) __a = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
30
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ : Optional[int] = logging.get_logger(__name__) lowerCamelCase__ : Tuple = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "swinv2" lowercase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Dict , _lowerCAmelCase : Optional[Any]=224 , _lowerCAmelCase : Optional[int]=4 , _lowerCAmelCase : Tuple=3 , _lowerCAmelCase : Tuple=96 , _lowerCAmelCase : Dict=[2, 2, 6, 2] , _lowerCAmelCase : Optional[Any]=[3, 6, 12, 24] , _lowerCAmelCase : str=7 , _lowerCAmelCase : List[Any]=4.0 , _lowerCAmelCase : List[str]=True , _lowerCAmelCase : List[Any]=0.0 , _lowerCAmelCase : List[Any]=0.0 , _lowerCAmelCase : Any=0.1 , _lowerCAmelCase : List[Any]="gelu" , _lowerCAmelCase : str=False , _lowerCAmelCase : str=0.02 , _lowerCAmelCase : List[Any]=1E-5 , _lowerCAmelCase : str=32 , **_lowerCAmelCase : List[Any] , ): super().__init__(**_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = patch_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = embed_dim SCREAMING_SNAKE_CASE_ = depths SCREAMING_SNAKE_CASE_ = len(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = num_heads SCREAMING_SNAKE_CASE_ = window_size SCREAMING_SNAKE_CASE_ = mlp_ratio SCREAMING_SNAKE_CASE_ = qkv_bias SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = drop_path_rate SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = use_absolute_embeddings SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE_ = int(embed_dim * 2 ** (len(_lowerCAmelCase ) - 1) ) SCREAMING_SNAKE_CASE_ = (0, 0, 0, 0)
31
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''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 _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''roberta''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : str=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = vocab_size __a : Tuple = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : str = hidden_act __a : Optional[Any] = intermediate_size __a : Dict = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Dict = type_vocab_size __a : str = initializer_range __a : List[str] = layer_norm_eps __a : Optional[int] = position_embedding_type __a : Union[str, Any] = use_cache __a : str = classifier_dropout class _UpperCamelCase( __lowerCamelCase ): @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' if self.task == "multiple-choice": __a : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ = { "configuration_instructblip": [ "INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "InstructBlipConfig", "InstructBlipQFormerConfig", "InstructBlipVisionConfig", ], "processing_instructblip": ["InstructBlipProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "InstructBlipQFormerModel", "InstructBlipPreTrainedModel", "InstructBlipForConditionalGeneration", "InstructBlipVisionModel", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
32
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''▁''' SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } SCREAMING_SNAKE_CASE__ = { '''facebook/xglm-564M''': 2048, } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="<unk>" , SCREAMING_SNAKE_CASE__ : Dict="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer __a : Any = 7 __a : Union[str, Any] = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words )] __a : Union[str, Any] = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) __a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Any = 1 # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __a : List[str] = len(self.sp_model ) __a : Optional[int] = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) __a : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[str] ): '''simple docstring''' __a : Tuple = self.__dict__.copy() __a : List[str] = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Dict = {} __a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a __a : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
# Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() lowerCamelCase__ : List[Any] = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model lowerCamelCase__ : int = { # fairseq: """wmt19-ru-en""": {"""length_penalty""": 1.1}, """wmt19-en-ru""": {"""length_penalty""": 1.1_5}, """wmt19-en-de""": {"""length_penalty""": 1.0}, """wmt19-de-en""": {"""length_penalty""": 1.1}, # allenai: """wmt16-en-de-dist-12-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-dist-6-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-12-1""": {"""length_penalty""": 0.8}, """wmt19-de-en-6-6-base""": {"""length_penalty""": 0.6}, """wmt19-de-en-6-6-big""": {"""length_penalty""": 0.6}, } # this remaps the different models to their organization names lowerCamelCase__ : List[str] = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCamelCase__ : Optional[int] = """facebook""" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: lowerCamelCase__ : int = """allenai""" def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Union[str, Any]: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} snake_case__ = dict((re.sub(r'''@@$''' , '''''' , __lowerCAmelCase ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''' , '''</w>''' , __lowerCAmelCase ), v) for k, v in d.items() ) snake_case__ = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[F"""{k}</w>"""] snake_case__ = d[k] # restore return da def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: # prep assert os.path.exists(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) print(F"""Writing results to {pytorch_dump_folder_path}""" ) # handle various types of models snake_case__ = basename(__lowerCAmelCase ) snake_case__ = dirname(__lowerCAmelCase ) snake_case__ = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel snake_case__ = cls.hub_models() snake_case__ = {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''} snake_case__ = '''.''' # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F"""using checkpoint {checkpoint_file}""" ) snake_case__ = hub_utils.from_pretrained( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase ) snake_case__ = vars(chkpt['''args''']['''model'''] ) snake_case__ = args['''source_lang'''] snake_case__ = args['''target_lang'''] snake_case__ = dirname(__lowerCAmelCase ) snake_case__ = basename(__lowerCAmelCase ) # dicts snake_case__ = os.path.join(__lowerCAmelCase , F"""dict.{src_lang}.txt""" ) snake_case__ = os.path.join(__lowerCAmelCase , F"""dict.{tgt_lang}.txt""" ) snake_case__ = Dictionary.load(__lowerCAmelCase ) snake_case__ = rewrite_dict_keys(src_dict.indices ) snake_case__ = len(__lowerCAmelCase ) snake_case__ = os.path.join(__lowerCAmelCase , '''vocab-src.json''' ) print(F"""Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records""" ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab snake_case__ = True for k in src_vocab.keys(): if not k.islower(): snake_case__ = False break snake_case__ = Dictionary.load(__lowerCAmelCase ) snake_case__ = rewrite_dict_keys(tgt_dict.indices ) snake_case__ = len(__lowerCAmelCase ) snake_case__ = os.path.join(__lowerCAmelCase , '''vocab-tgt.json''' ) print(F"""Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records""" ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # merges_file (bpecodes) snake_case__ = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES['''merges_file'''] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" snake_case__ = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): break with open(__lowerCAmelCase , encoding='''utf-8''' ) as fin: snake_case__ = fin.read() snake_case__ = re.sub(r''' \d+$''' , '''''' , __lowerCAmelCase , 0 , re.M ) # remove frequency number print(F"""Generating {merges_file}""" ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as fout: fout.write(__lowerCAmelCase ) # model config snake_case__ = os.path.join(__lowerCAmelCase , '''config.json''' ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F"""need to extend tokenizer to support bpe={args['bpe']}""" assert args["tokenizer"] == "moses", F"""need to extend tokenizer to support bpe={args['tokenizer']}""" snake_case__ = { '''architectures''': ['''FSMTForConditionalGeneration'''], '''model_type''': '''fsmt''', '''activation_dropout''': args['''activation_dropout'''], '''activation_function''': '''relu''', '''attention_dropout''': args['''attention_dropout'''], '''d_model''': args['''decoder_embed_dim'''], '''dropout''': args['''dropout'''], '''init_std''': 0.02, '''max_position_embeddings''': args['''max_source_positions'''], '''num_hidden_layers''': args['''encoder_layers'''], '''src_vocab_size''': src_vocab_size, '''tgt_vocab_size''': tgt_vocab_size, '''langs''': [src_lang, tgt_lang], '''encoder_attention_heads''': args['''encoder_attention_heads'''], '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''], '''encoder_layerdrop''': args['''encoder_layerdrop'''], '''encoder_layers''': args['''encoder_layers'''], '''decoder_attention_heads''': args['''decoder_attention_heads'''], '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''], '''decoder_layerdrop''': args['''decoder_layerdrop'''], '''decoder_layers''': args['''decoder_layers'''], '''bos_token_id''': 0, '''pad_token_id''': 1, '''eos_token_id''': 2, '''is_encoder_decoder''': True, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_all_embeddings'''], } # good hparam defaults to start with snake_case__ = 5 snake_case__ = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: snake_case__ = best_score_hparams[model_dir]['''length_penalty'''] else: snake_case__ = 1.0 print(F"""Generating {fsmt_model_config_file}""" ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # tokenizer config snake_case__ = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = { '''langs''': [src_lang, tgt_lang], '''model_max_length''': 1024, '''do_lower_case''': do_lower_case, } print(F"""Generating {fsmt_tokenizer_config_file}""" ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # model snake_case__ = chkpt['''models'''][0] snake_case__ = model.state_dict() # rename keys to start with 'model.' snake_case__ = OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys snake_case__ = [ '''model.model''', '''model.encoder.version''', '''model.decoder.version''', '''model.encoder_embed_tokens.weight''', '''model.decoder_embed_tokens.weight''', '''model.encoder.embed_positions._float_tensor''', '''model.decoder.embed_positions._float_tensor''', ] for k in ignore_keys: model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = FSMTConfig.from_pretrained(__lowerCAmelCase ) snake_case__ = FSMTForConditionalGeneration(__lowerCAmelCase ) # check that it loads ok model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) # save snake_case__ = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) print(F"""Generating {pytorch_weights_dump_path}""" ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) print('''Conversion is done!''' ) print('''\nLast step is to upload the files to s3''' ) print(F"""cd {data_root}""" ) print(F"""transformers-cli upload {model_dir}""" ) if __name__ == "__main__": lowerCamelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--fsmt_checkpoint_path""", default=None, type=str, required=True, help=( """Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,""" """ bpecodes, etc.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCamelCase__ : Dict = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
33
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] SCREAMING_SNAKE_CASE__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] ): __a : str = torch.load(lowerCamelCase_ , map_location='cpu' ) return sd def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict=rename_keys_prefix ): __a : Optional[Any] = OrderedDict() __a : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a : List[Any] = key for name_pair in rename_keys_prefix: __a : List[str] = new_key.replace(name_pair[0] , name_pair[1] ) __a : Any = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a : int = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : Any ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a : Dict = 'pretraining' if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __a : int = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __a : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} __a : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __a : Any = {'visual_embedding_dim': 2_0_4_8} __a : List[str] = 'vqa_advanced' elif "vqa" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __a : List[Any] = 'vqa' elif "nlvr" in checkpoint_path: __a : Optional[int] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __a : Optional[Any] = 'nlvr' __a : str = VisualBertConfig(**lowerCamelCase_ ) # Load State Dict __a : str = load_state_dict(lowerCamelCase_ ) __a : str = get_new_dict(lowerCamelCase_ , lowerCamelCase_ ) if model_type == "pretraining": __a : Optional[Any] = VisualBertForPreTraining(lowerCamelCase_ ) elif model_type == "vqa": __a : Any = VisualBertForQuestionAnswering(lowerCamelCase_ ) elif model_type == "nlvr": __a : int = VisualBertForVisualReasoning(lowerCamelCase_ ) elif model_type == "multichoice": __a : Optional[int] = VisualBertForMultipleChoice(lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # Save Checkpoints Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
47
0
"""simple docstring""" from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image SCREAMING_SNAKE_CASE_ = ['text', 'image', 'audio'] def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(_lowercase ,_lowercase ): inputs.append(create_inputs(_lowercase ) ) else: raise ValueError(f'Invalid type requested: {input_type}' ) return inputs def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = [] for output in outputs: if isinstance(_lowercase ,(str, AgentText) ): output_types.append('''text''' ) elif isinstance(_lowercase ,(Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(_lowercase ,(torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(f'Invalid output: {output}' ) return output_types @is_tool_test class snake_case_ : """simple docstring""" def UpperCAmelCase__ ( self) -> List[Any]: self.assertTrue(hasattr(self.tool , '''inputs''')) self.assertTrue(hasattr(self.tool , '''outputs''')) UpperCamelCase = self.tool.inputs for _input in inputs: if isinstance(_input , lowerCamelCase_): for __input in _input: self.assertTrue(__input in authorized_types) else: self.assertTrue(_input in authorized_types) UpperCamelCase = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types) def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = create_inputs(self.tool.inputs) UpperCamelCase = self.tool(*lowerCamelCase_) # There is a single output if len(self.tool.outputs) == 1: UpperCamelCase = [outputs] self.assertListEqual(output_types(lowerCamelCase_) , self.tool.outputs) def UpperCAmelCase__ ( self) -> str: self.assertTrue(hasattr(self.tool , '''description''')) self.assertTrue(hasattr(self.tool , '''default_checkpoint''')) self.assertTrue(self.tool.description.startswith('''This is a tool that''')) def UpperCAmelCase__ ( self) -> Any: UpperCamelCase = create_inputs(self.tool.inputs) UpperCamelCase = self.tool(*lowerCamelCase_) if not isinstance(lowerCamelCase_ , lowerCamelCase_): UpperCamelCase = [outputs] self.assertEqual(len(lowerCamelCase_) , len(self.tool.outputs)) for output, output_type in zip(lowerCamelCase_ , self.tool.outputs): UpperCamelCase = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(lowerCamelCase_ , lowerCamelCase_)) def UpperCAmelCase__ ( self) -> List[Any]: UpperCamelCase = create_inputs(self.tool.inputs) UpperCamelCase = [] for _input, input_type in zip(lowerCamelCase_ , self.tool.inputs): if isinstance(lowerCamelCase_ , lowerCamelCase_): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type]) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input)) # Should not raise an error UpperCamelCase = self.tool(*lowerCamelCase_) if not isinstance(lowerCamelCase_ , lowerCamelCase_): UpperCamelCase = [outputs] self.assertEqual(len(lowerCamelCase_) , len(self.tool.outputs))
34
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
47
0
import random def a ( A__ ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = num - 1 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 while s % 2 == 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = s // 2 t += 1 for _ in range(5 ): SCREAMING_SNAKE_CASE__ : int = random.randrange(2 , num - 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pow(A__ , A__ , A__ ) if v != 1: SCREAMING_SNAKE_CASE__ : List[str] = 0 while v != (num - 1): if i == t - 1: return False else: SCREAMING_SNAKE_CASE__ : Any = i + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = (v**2) % num return True def a ( A__ ) -> bool: '''simple docstring''' if num < 2: return False SCREAMING_SNAKE_CASE__ : Optional[int] = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(A__ ) def a ( A__ = 1_0_2_4 ) -> int: '''simple docstring''' while True: SCREAMING_SNAKE_CASE__ : Any = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(A__ ): return num if __name__ == "__main__": a_ :Dict = generate_large_prime() print(('Prime number:', num)) print(('is_prime_low_num:', is_prime_low_num(num)))
35
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class _UpperCamelCase( __lowerCamelCase ): def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[Any] = tempfile.mkdtemp() __a : int = 8 # DPR tok __a : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , 'dpr_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_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] ) ) # BART tok __a : str = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __a : Optional[int] = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __a : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : List[str] = {'unk_token': '<unk>'} __a : Dict = os.path.join(self.tmpdirname , 'bart_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['vocab_file'] ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowerCAmelCase ( self : str ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) ) def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Tuple = os.path.join(self.tmpdirname , 'rag_tokenizer' ) __a : Optional[Any] = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) __a : Optional[Any] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Optional[Any] = RagTokenizer.from_pretrained('facebook/rag-token-nq' ) __a : List[Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Any = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' ) __a : Union[str, Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : str = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
47
0
import gc import threading import time import psutil import torch class _A : '''simple docstring''' def __init__( self ): '''simple docstring''' snake_case : Union[str, Any] = psutil.Process() snake_case : Union[str, Any] = False def snake_case_ ( self ): '''simple docstring''' snake_case : List[Any] = -1 while True: snake_case : List[str] = max(self.process.memory_info().rss ,self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def snake_case_ ( self ): '''simple docstring''' snake_case : Optional[int] = True snake_case : Optional[Any] = threading.Thread(target=self.peak_monitor ) snake_case : int = True self.thread.start() def snake_case_ ( self ): '''simple docstring''' snake_case : str = False self.thread.join() return self.cpu_memory_peak __lowercase : int = PeakCPUMemory() def lowercase ( ) -> List[str]: '''simple docstring''' snake_case : Union[str, Any] = {"""time""": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem snake_case : str = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): snake_case : Union[str, Any] = torch.cuda.memory_allocated(__A ) torch.cuda.reset_peak_memory_stats() return measures def lowercase ( __A : str ) -> List[str]: '''simple docstring''' snake_case : Any = {"""time""": time.time() - start_measures["""time"""]} gc.collect() torch.cuda.empty_cache() # CPU mem snake_case : Union[str, Any] = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20 snake_case : List[str] = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): snake_case : List[Any] = (torch.cuda.memory_allocated(__A ) - start_measures[str(__A )]) / 2**20 snake_case : Optional[int] = (torch.cuda.max_memory_allocated(__A ) - start_measures[str(__A )]) / 2**20 return measures def lowercase ( __A : Dict , __A : Optional[int] ) -> Dict: '''simple docstring''' print(f"""{description}:""" ) print(f"""- Time: {measures["time"]:.2f}s""" ) for i in range(torch.cuda.device_count() ): print(f"""- GPU {i} allocated: {measures[str(__A )]:.2f}MiB""" ) snake_case : Tuple = measures[f"""{i}-peak"""] print(f"""- GPU {i} peak: {peak:.2f}MiB""" ) print(f"""- CPU RAM allocated: {measures["cpu"]:.2f}MiB""" ) print(f"""- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB""" )
36
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''spiece.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } SCREAMING_SNAKE_CASE__ = {'''bert_for_seq_generation''': 512} class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : int = ['''input_ids''', '''attention_mask'''] def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : Any="<unk>" , SCREAMING_SNAKE_CASE__ : int="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="<::::>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : int = vocab_file __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): '''simple docstring''' __a : Union[str, Any] = self.__dict__.copy() __a : Any = None return state def __setstate__( self : int , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' __a : str = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : str = {} __a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' __a : int = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Optional[Any] = [] __a : Optional[int] = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token __a : Dict = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Tuple = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
from itertools import permutations def UpperCamelCase_ ( __a ) -> bool: if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False a__ : Tuple = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def UpperCamelCase_ ( __a = 10 ) -> int: return sum( int("".join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f"""{solution() = }""")
37
from ..utils import DummyObject, requires_backends class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Any = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Dict , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] )
47
0
'''simple docstring''' from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging A_ : Dict = logging.get_logger(__name__) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''audio_values''', '''audio_mask'''] def __init__( self , __SCREAMING_SNAKE_CASE=2_0_4_8 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=[1_6, 1_6] , __SCREAMING_SNAKE_CASE=1_2_8 , __SCREAMING_SNAKE_CASE=4_4_1_0_0 , __SCREAMING_SNAKE_CASE=8_6 , __SCREAMING_SNAKE_CASE=2_0_4_8 , __SCREAMING_SNAKE_CASE=0.0 , **__SCREAMING_SNAKE_CASE , ): super().__init__( feature_size=__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , padding_value=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) snake_case__ : Tuple = spectrogram_length snake_case__ : List[Any] = num_channels snake_case__ : List[str] = patch_size snake_case__ : Dict = feature_size // self.patch_size[1] snake_case__ : Optional[Any] = n_fft snake_case__ : Optional[int] = sampling_rate // hop_length_to_sampling_rate snake_case__ : Optional[int] = sampling_rate snake_case__ : str = padding_value snake_case__ : Tuple = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__SCREAMING_SNAKE_CASE , min_frequency=0.0 , max_frequency=2_2050.0 , sampling_rate=__SCREAMING_SNAKE_CASE , norm="""slaney""" , mel_scale="""slaney""" , ).T def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = spectrogram( __SCREAMING_SNAKE_CASE , window_function(self.n_fft , """hann""" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel="""dB""" , db_range=80.0 , ) snake_case__ : List[str] = log_spec[:, :-1] snake_case__ : Optional[Any] = log_spec - 20.0 snake_case__ : List[str] = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , **__SCREAMING_SNAKE_CASE , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( """This feature extractor is set to support sampling rate""" f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled" f" with {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) snake_case__ : List[str] = isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"Only mono-channel audio is supported for input to {self}" ) snake_case__ : int = is_batched_numpy or ( isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case__ : Union[str, Any] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ): snake_case__ : Optional[int] = np.asarray(__SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): snake_case__ : int = raw_speech.astype(np.floataa ) # always return batch if not is_batched: snake_case__ : Union[str, Any] = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis snake_case__ : str = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = [np.asarray(__SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask snake_case__ : Union[str, Any] = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: snake_case__ : int = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] snake_case__ : List[str] = np.array(__SCREAMING_SNAKE_CASE ).astype(np.floataa ) # convert into correct format for padding snake_case__ : Tuple = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch snake_case__ : Dict = np.ones([len(__SCREAMING_SNAKE_CASE ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) snake_case__ : int = padded_audio_features * self.padding_value for i in range(len(__SCREAMING_SNAKE_CASE ) ): snake_case__ : str = audio_features[i] snake_case__ : Tuple = feature # return as BatchFeature if return_attention_mask: snake_case__ : int = {"""audio_values""": padded_audio_features, """audio_mask""": audio_mask} else: snake_case__ : Any = {"""audio_values""": padded_audio_features} snake_case__ : Union[str, Any] = BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE ) return encoded_inputs
38
import math from datetime import datetime, timedelta def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Union[str, Any] = year % 1_9 __a : int = year % 4 __a : Optional[int] = year % 7 __a : Dict = math.floor(year / 1_0_0 ) __a : Optional[Any] = math.floor((1_3 + 8 * leap_day_inhibits) / 2_5 ) __a : Union[str, Any] = leap_day_inhibits / 4 __a : str = ( 1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 3_0 __a : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __a : List[Any] = (1_9 * metonic_cycle + secular_moon_shift) % 3_0 # PHM -> Paschal Full Moon __a : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 2_9 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_9 ) elif days_to_add == 2_8 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_8 ) else: return datetime(lowerCamelCase_ , 3 , 2_2 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): SCREAMING_SNAKE_CASE__ = '''will be''' if year > datetime.now().year else '''was''' print(F"Easter in {year} {tense} {gauss_easter(year)}")
47
0
from __future__ import annotations import math from collections.abc import Callable def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 100 , ): snake_case_ = x_start snake_case_ = fnc(SCREAMING_SNAKE_CASE__ ) snake_case_ = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates curve as a sequence of linear lines and sums their length snake_case_ = (x_end - x_start) / steps + xa snake_case_ = fnc(SCREAMING_SNAKE_CASE__ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step snake_case_ = xa snake_case_ = fxa return length if __name__ == "__main__": def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): return math.sin(10 * x ) print('''f(x) = sin(10 * x)''') print('''The length of the curve from x = -10 to x = 10 is:''') lowerCAmelCase_ = 10 while i <= 10_00_00: print(f"""With {i} steps: {line_length(f, -10, 10, i)}""") i *= 10
39
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = '''informer''' __SCREAMING_SNAKE_CASE : List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "student_t" , SCREAMING_SNAKE_CASE__ : str = "nll" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : List[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : int = 6_4 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.05 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str = "prob" , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Dict = prediction_length __a : Tuple = context_length or prediction_length __a : Tuple = distribution_output __a : Tuple = loss __a : str = input_size __a : Dict = num_time_features __a : Optional[int] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __a : str = scaling __a : Tuple = num_dynamic_real_features __a : int = num_static_real_features __a : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __a : Optional[Any] = cardinality else: __a : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __a : int = embedding_dimension else: __a : List[Any] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] __a : int = num_parallel_samples # Transformer architecture configuration __a : str = input_size * len(self.lags_sequence ) + self._number_of_features __a : Optional[int] = d_model __a : Union[str, Any] = encoder_attention_heads __a : int = decoder_attention_heads __a : Any = encoder_ffn_dim __a : Union[str, Any] = decoder_ffn_dim __a : List[Any] = encoder_layers __a : Optional[int] = decoder_layers __a : int = dropout __a : Optional[Any] = attention_dropout __a : Dict = activation_dropout __a : Union[str, Any] = encoder_layerdrop __a : Optional[int] = decoder_layerdrop __a : List[str] = activation_function __a : str = init_std __a : Optional[int] = use_cache # Informer __a : Union[str, Any] = attention_type __a : str = sampling_factor __a : Dict = distil super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
0
import itertools import math def UpperCamelCase ( snake_case__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCamelCase ( ) -> List[Any]: UpperCamelCase : List[str] = 2 while True: if is_prime(snake_case__ ): yield num num += 1 def UpperCamelCase ( snake_case__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , snake_case__ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
40
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE : Union[str, Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : List[str] = 1_0, 0.0 __a : Dict = self.dummy_model() __a : str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __a : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config(steps_offset=1 ) __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 1_0, 5_0] , [1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for t, eta in zip([1, 1_0, 4_9] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 , 4_0_0 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 , 9_6_0 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 , 4_8_6 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 , 9_9_8 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config() __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : Any = 1_0, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = self.dummy_model() __a : int = self.dummy_sample_deter __a : List[Any] = self.dummy_sample_deter + 0.1 __a : List[str] = self.dummy_sample_deter - 0.1 __a : Optional[Any] = samplea.shape[0] __a : Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) __a : Union[str, Any] = torch.arange(SCREAMING_SNAKE_CASE__ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE__ ) __a : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a : int = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE__ ) __a : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : List[str] = self.full_loop() __a : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : Dict = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
47
0
'''simple docstring''' import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''facebook/detr-resnet-50''': '''https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json''', # See all DETR models at https://huggingface.co/models?filter=detr } class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = 'detr' SCREAMING_SNAKE_CASE : List[str] = ['past_key_values'] SCREAMING_SNAKE_CASE : Any = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : int ,lowercase__ : Dict=True ,lowercase__ : Optional[Any]=None ,lowercase__ : str=3 ,lowercase__ : Optional[int]=1_0_0 ,lowercase__ : Optional[int]=6 ,lowercase__ : Optional[Any]=2_0_4_8 ,lowercase__ : Any=8 ,lowercase__ : int=6 ,lowercase__ : Any=2_0_4_8 ,lowercase__ : Any=8 ,lowercase__ : List[str]=0.0 ,lowercase__ : Union[str, Any]=0.0 ,lowercase__ : Union[str, Any]=True ,lowercase__ : str="relu" ,lowercase__ : int=2_5_6 ,lowercase__ : int=0.1 ,lowercase__ : Tuple=0.0 ,lowercase__ : Tuple=0.0 ,lowercase__ : int=0.0_2 ,lowercase__ : Dict=1.0 ,lowercase__ : str=False ,lowercase__ : Union[str, Any]="sine" ,lowercase__ : List[str]="resnet50" ,lowercase__ : Dict=True ,lowercase__ : List[Any]=False ,lowercase__ : Union[str, Any]=1 ,lowercase__ : Union[str, Any]=5 ,lowercase__ : Tuple=2 ,lowercase__ : str=1 ,lowercase__ : List[Any]=1 ,lowercase__ : Dict=5 ,lowercase__ : Optional[Any]=2 ,lowercase__ : int=0.1 ,**lowercase__ : Dict ,): if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __lowercase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(lowercase__ ,lowercase__ ): __lowercase = backbone_config.get('''model_type''' ) __lowercase = CONFIG_MAPPING[backbone_model_type] __lowercase = config_class.from_dict(lowercase__ ) # set timm attributes to None __lowercase , __lowercase , __lowercase = None, None, None __lowercase = use_timm_backbone __lowercase = backbone_config __lowercase = num_channels __lowercase = num_queries __lowercase = d_model __lowercase = encoder_ffn_dim __lowercase = encoder_layers __lowercase = encoder_attention_heads __lowercase = decoder_ffn_dim __lowercase = decoder_layers __lowercase = decoder_attention_heads __lowercase = dropout __lowercase = attention_dropout __lowercase = activation_dropout __lowercase = activation_function __lowercase = init_std __lowercase = init_xavier_std __lowercase = encoder_layerdrop __lowercase = decoder_layerdrop __lowercase = encoder_layers __lowercase = auxiliary_loss __lowercase = position_embedding_type __lowercase = backbone __lowercase = use_pretrained_backbone __lowercase = dilation # Hungarian matcher __lowercase = class_cost __lowercase = bbox_cost __lowercase = giou_cost # Loss coefficients __lowercase = mask_loss_coefficient __lowercase = dice_loss_coefficient __lowercase = bbox_loss_coefficient __lowercase = giou_loss_coefficient __lowercase = eos_coefficient super().__init__(is_encoder_decoder=lowercase__ ,**lowercase__ ) @property def SCREAMING_SNAKE_CASE ( self : Any ): return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): return self.d_model @classmethod def SCREAMING_SNAKE_CASE ( cls : int ,lowercase__ : PretrainedConfig ,**lowercase__ : Any ): return cls(backbone_config=lowercase__ ,**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: __lowercase = self.backbone_config.to_dict() __lowercase = self.__class__.model_type return output class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE ( self : Dict ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self : List[str] ): return 1e-5 @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return 1_2
41
def UpperCAmelCase__ ( lowerCamelCase_ : list[int] , lowerCamelCase_ : list[int] ): # Check if the input is valid if not len(lowerCamelCase_ ) == len(lowerCamelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __a , __a , __a : Optional[Any] = equationa __a , __a , __a : Optional[int] = equationa # Calculate the determinants of the matrices __a : str = aa * ba - aa * ba __a : Tuple = ca * ba - ca * ba __a : Union[str, Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __a : Any = determinant_x / determinant __a : Optional[Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
47
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ = logging.get_logger(__name__) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = size if size is not None else {'shortest_edge': 384} lowerCamelCase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_resize lowerCamelCase_ = size # Default value set here for backwards compatibility where the value in config is None lowerCamelCase_ = crop_pct if crop_pct is not None else 224 / 256 lowerCamelCase_ = resample lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_factor lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: '''simple docstring''' lowerCamelCase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(f'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''' ) lowerCamelCase_ = size['shortest_edge'] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCamelCase_ = int(shortest_edge / crop_pct ) lowerCamelCase_ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE_ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE_ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: '''simple docstring''' return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ) -> PIL.Image.Image: '''simple docstring''' lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = crop_pct if crop_pct is not None else self.crop_pct lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ = image_std if image_std is not None else self.image_std lowerCamelCase_ = size if size is not None else self.size lowerCamelCase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: lowerCamelCase_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , crop_pct=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] lowerCamelCase_ = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
42
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
47
0
from __future__ import annotations from collections.abc import Sequence from typing import Literal def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = list(SCREAMING_SNAKE_CASE ) lowercase__ = list(SCREAMING_SNAKE_CASE ) lowercase__ = 0 for i in range(len(SCREAMING_SNAKE_CASE ) ): if lista[i] != lista[i]: count += 1 lowercase__ = '''_''' if count > 1: return False else: return "".join(SCREAMING_SNAKE_CASE ) def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [] while True: lowercase__ = ['''$'''] * len(SCREAMING_SNAKE_CASE ) lowercase__ = [] for i in range(len(SCREAMING_SNAKE_CASE ) ): for j in range(i + 1 , len(SCREAMING_SNAKE_CASE ) ): lowercase__ = compare_string(binary[i] , binary[j] ) if k is False: lowercase__ = '''*''' lowercase__ = '''*''' temp.append('''X''' ) for i in range(len(SCREAMING_SNAKE_CASE ) ): if checka[i] == "$": pi.append(binary[i] ) if len(SCREAMING_SNAKE_CASE ) == 0: return pi lowercase__ = list(set(SCREAMING_SNAKE_CASE ) ) def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [] for minterm in minterms: lowercase__ = '''''' for _ in range(SCREAMING_SNAKE_CASE ): lowercase__ = str(minterm % 2 ) + string minterm //= 2 temp.append(SCREAMING_SNAKE_CASE ) return temp def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = list(SCREAMING_SNAKE_CASE ) lowercase__ = list(SCREAMING_SNAKE_CASE ) lowercase__ = 0 for i in range(len(SCREAMING_SNAKE_CASE ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [] lowercase__ = [0] * len(SCREAMING_SNAKE_CASE ) for i in range(len(chart[0] ) ): lowercase__ = 0 lowercase__ = -1 for j in range(len(SCREAMING_SNAKE_CASE ) ): if chart[j][i] == 1: count += 1 lowercase__ = j if count == 1: lowercase__ = 1 for i in range(len(SCREAMING_SNAKE_CASE ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(SCREAMING_SNAKE_CASE ) ): lowercase__ = 0 temp.append(prime_implicants[i] ) while True: lowercase__ = 0 lowercase__ = -1 lowercase__ = 0 for i in range(len(SCREAMING_SNAKE_CASE ) ): lowercase__ = chart[i].count(1 ) if count_n > max_n: lowercase__ = count_n lowercase__ = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(SCREAMING_SNAKE_CASE ) ): lowercase__ = 0 def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [[0 for x in range(len(SCREAMING_SNAKE_CASE ) )] for x in range(len(SCREAMING_SNAKE_CASE ) )] for i in range(len(SCREAMING_SNAKE_CASE ) ): lowercase__ = prime_implicants[i].count('''_''' ) for j in range(len(SCREAMING_SNAKE_CASE ) ): if is_for_table(prime_implicants[i] , binary[j] , SCREAMING_SNAKE_CASE ): lowercase__ = 1 return chart def _a ( ): """simple docstring""" lowercase__ = int(input('''Enter the no. of variables\n''' ) ) lowercase__ = [ float(SCREAMING_SNAKE_CASE ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] lowercase__ = decimal_to_binary(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ = check(SCREAMING_SNAKE_CASE ) print('''Prime Implicants are:''' ) print(SCREAMING_SNAKE_CASE ) lowercase__ = prime_implicant_chart(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ = selection(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print('''Essential Prime Implicants are:''' ) print(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() main()
43
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
47
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class UpperCAmelCase__ ( unittest.TestCase ): def __init__( self : Optional[int],__A : Any,__A : Tuple=7,__A : List[Any]=3,__A : str=1_8,__A : Tuple=3_0,__A : Dict=4_0_0,__A : int=True,__A : List[Any]=None,__A : Any=True,__A : int=False,__A : str=True,__A : int=True,__A : Any=[0.5, 0.5, 0.5],__A : Dict=[0.5, 0.5, 0.5],): _lowerCamelCase : str = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : List[Any] = num_channels _lowerCamelCase : Dict = image_size _lowerCamelCase : Tuple = min_resolution _lowerCamelCase : List[str] = max_resolution _lowerCamelCase : str = do_resize _lowerCamelCase : int = size if size is not None else {"height": 1_8, "width": 2_0} _lowerCamelCase : Union[str, Any] = do_thumbnail _lowerCamelCase : Optional[int] = do_align_axis _lowerCamelCase : Any = do_pad _lowerCamelCase : Tuple = do_normalize _lowerCamelCase : str = image_mean _lowerCamelCase : int = image_std def lowerCamelCase_ ( self : List[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class UpperCAmelCase__ ( A , unittest.TestCase ): lowerCAmelCase_ = DonutImageProcessor if is_vision_available() else None def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : int = DonutImageProcessingTester(self ) @property def lowerCamelCase_ ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase_ ( self : Tuple ): _lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A,"do_resize" ) ) self.assertTrue(hasattr(__A,"size" ) ) self.assertTrue(hasattr(__A,"do_thumbnail" ) ) self.assertTrue(hasattr(__A,"do_align_long_axis" ) ) self.assertTrue(hasattr(__A,"do_pad" ) ) self.assertTrue(hasattr(__A,"do_normalize" ) ) self.assertTrue(hasattr(__A,"image_mean" ) ) self.assertTrue(hasattr(__A,"image_std" ) ) def lowerCamelCase_ ( self : Tuple ): _lowerCamelCase : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size,{"height": 1_8, "width": 2_0} ) _lowerCamelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict,size=4_2 ) self.assertEqual(image_processor.size,{"height": 4_2, "width": 4_2} ) # Previous config had dimensions in (width, height) order _lowerCamelCase : Any = self.image_processing_class.from_dict(self.image_processor_dict,size=(4_2, 8_4) ) self.assertEqual(image_processor.size,{"height": 8_4, "width": 4_2} ) def lowerCamelCase_ ( self : List[Any] ): pass @is_flaky() def lowerCamelCase_ ( self : Dict ): # Initialize image_processing _lowerCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCamelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A,Image.Image ) # Test not batched input _lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0],return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),) # Test batched _lowerCamelCase : int = image_processing(__A,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),) @is_flaky() def lowerCamelCase_ ( self : List[str] ): # Initialize image_processing _lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,numpify=__A ) for image in image_inputs: self.assertIsInstance(__A,np.ndarray ) # Test not batched input _lowerCamelCase : List[Any] = image_processing(image_inputs[0],return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),) # Test batched _lowerCamelCase : List[Any] = image_processing(__A,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),) @is_flaky() def lowerCamelCase_ ( self : Optional[Any] ): # Initialize image_processing _lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,torchify=__A ) for image in image_inputs: self.assertIsInstance(__A,torch.Tensor ) # Test not batched input _lowerCamelCase : Tuple = image_processing(image_inputs[0],return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),) # Test batched _lowerCamelCase : int = image_processing(__A,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ),)
44
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
0
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def A ( lowercase__ : Any , lowercase__ : List[Any] , lowercase__ : int , lowercase__ : Optional[Any] ) -> Optional[Any]: if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :Tuple = np.full((len(lowercase__ ), sequence_length, 2) , lowercase__ ) else: UpperCamelCase__ :List[str] = np.full((len(lowercase__ ), sequence_length) , lowercase__ ) for i, tensor in enumerate(lowercase__ ): if padding_side == "right": if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :List[Any] = tensor[:sequence_length] else: UpperCamelCase__ :Dict = tensor[:sequence_length] else: if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :Optional[int] = tensor[:sequence_length] else: UpperCamelCase__ :Optional[int] = tensor[:sequence_length] return out_tensor.tolist() def A ( lowercase__ : Dict ) -> Optional[Any]: UpperCamelCase__ :List[Any] = ord(lowercase__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True UpperCamelCase__ :str = unicodedata.category(lowercase__ ) if cat.startswith("""P""" ): return True return False @dataclass class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : PreTrainedTokenizerBase _snake_case : Union[bool, str, PaddingStrategy] = True _snake_case : Optional[int] = None _snake_case : Optional[int] = None _snake_case : int = -100 _snake_case : str = "pt" def __a ( self :Any , lowerCamelCase__ :int ): import torch UpperCamelCase__ :str = """label""" if """label""" in features[0].keys() else """labels""" UpperCamelCase__ :str = [feature[label_name] for feature in features] if label_name in features[0].keys() else None UpperCamelCase__ :Any = self.tokenizer.pad( lowerCamelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch UpperCamelCase__ :List[Any] = torch.tensor(batch["""entity_ids"""] ).shape[1] UpperCamelCase__ :Optional[int] = self.tokenizer.padding_side if padding_side == "right": UpperCamelCase__ :Optional[Any] = [ list(lowerCamelCase__ ) + [self.label_pad_token_id] * (sequence_length - len(lowerCamelCase__ )) for label in labels ] else: UpperCamelCase__ :Union[str, Any] = [ [self.label_pad_token_id] * (sequence_length - len(lowerCamelCase__ )) + list(lowerCamelCase__ ) for label in labels ] UpperCamelCase__ :Optional[Any] = [feature["""ner_tags"""] for feature in features] UpperCamelCase__ :Optional[int] = padding_tensor(lowerCamelCase__ , -1 , lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = [feature["""original_entity_spans"""] for feature in features] UpperCamelCase__ :Tuple = padding_tensor(lowerCamelCase__ , (-1, -1) , lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :int = {k: torch.tensor(lowerCamelCase__ , dtype=torch.intaa ) for k, v in batch.items()} return batch
45
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''sew-d''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=("p2c", "c2p") , SCREAMING_SNAKE_CASE__ : str="layer_norm" , SCREAMING_SNAKE_CASE__ : Tuple="gelu_python" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-7 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Optional[int]="group" , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : str=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2_8 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]="mean" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=2_5_6 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = hidden_size __a : Optional[Any] = feat_extract_norm __a : List[str] = feat_extract_activation __a : Dict = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = list(SCREAMING_SNAKE_CASE__ ) __a : List[str] = list(SCREAMING_SNAKE_CASE__ ) __a : int = conv_bias __a : Tuple = num_conv_pos_embeddings __a : List[str] = num_conv_pos_embedding_groups __a : Optional[Any] = len(self.conv_dim ) __a : Union[str, Any] = num_hidden_layers __a : Optional[Any] = intermediate_size __a : Union[str, Any] = squeeze_factor __a : List[Any] = max_position_embeddings __a : Tuple = position_buckets __a : Optional[int] = share_att_key __a : List[str] = relative_attention __a : Any = norm_rel_ebd __a : Any = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = hidden_act __a : str = num_attention_heads __a : Union[str, Any] = hidden_dropout __a : Optional[int] = attention_dropout __a : List[str] = activation_dropout __a : int = feat_proj_dropout __a : int = final_dropout __a : Dict = layer_norm_eps __a : Tuple = feature_layer_norm_eps __a : str = initializer_range __a : Tuple = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : Tuple = apply_spec_augment __a : Optional[Any] = mask_time_prob __a : Any = mask_time_length __a : List[str] = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Tuple = mask_feature_length __a : Any = mask_feature_min_masks # ctc loss __a : Optional[int] = ctc_loss_reduction __a : List[Any] = ctc_zero_infinity # sequence classification __a : Dict = use_weighted_layer_sum __a : Optional[Any] = classifier_proj_size @property def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
47
0
"""simple docstring""" def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> int: '''simple docstring''' while second != 0: _lowerCamelCase : int = first & second first ^= second _lowerCamelCase : str = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase : Tuple = int(input('''Enter the first number: ''').strip()) _lowerCAmelCase : Union[str, Any] = int(input('''Enter the second number: ''').strip()) print(f'''{add(first, second) = }''')
46
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
0
'''simple docstring''' from manim import * class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = Rectangle(height=0.5 , width=0.5 ) lowerCAmelCase__ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = VGroup(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("CPU" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(4 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("GPU" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) gpu.move_to([-1, -1, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("Model" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) model.move_to([3, -1.0, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [] for i, rect in enumerate(__magic_name__ ): rect.set_stroke(__magic_name__ ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) lowerCAmelCase__ = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__magic_name__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__magic_name__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__magic_name__ , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__magic_name__ , buff=0.0 ) self.add(__magic_name__ ) cpu_targs.append(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("Loaded Checkpoint" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , aligned_edge=__magic_name__ , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) lowerCAmelCase__ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCAmelCase__ = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(__magic_name__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) lowerCAmelCase__ = MarkupText( f"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__magic_name__ ) , Write(__magic_name__ ) ) self.play(Write(__magic_name__ , run_time=1 ) , Create(__magic_name__ , run_time=1 ) ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] for i, rect in enumerate(__magic_name__ ): lowerCAmelCase__ = fill.copy().set_fill(__magic_name__ , opacity=0.7 ) target.move_to(__magic_name__ ) first_animations.append(GrowFromCenter(__magic_name__ , run_time=1 ) ) lowerCAmelCase__ = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__magic_name__ , run_time=1.5 ) ) self.play(*__magic_name__ ) self.play(*__magic_name__ ) self.wait()
48
from collections.abc import Sequence from queue import Queue class _UpperCamelCase: def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None ): '''simple docstring''' __a : Tuple = start __a : Dict = end __a : List[str] = val __a : List[Any] = (start + end) // 2 __a : Optional[Any] = left __a : List[str] = right def __repr__( self : Dict ): '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class _UpperCamelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Sequence , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Tuple = collection __a : Dict = function if self.collection: __a : int = self._build_tree(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.collection[start] ) __a : Tuple = (start + end) // 2 __a : Optional[int] = self._build_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Tuple = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE__ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if node.start == i and node.end == i: __a : Optional[Any] = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = self.fn(node.left.val , node.right.val ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE__ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE__ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' if self.root is not None: __a : Tuple = Queue() queue.put(self.root ) while not queue.empty(): __a : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) SCREAMING_SNAKE_CASE__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
47
0
"""simple docstring""" 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 _UpperCAmelCase : def __init__( self : Optional[Any] , _lowercase : Any , _lowercase : List[str]=13 , _lowercase : List[Any]=7 , _lowercase : Optional[int]=True , _lowercase : Optional[Any]=True , _lowercase : Optional[int]=True , _lowercase : str=True , _lowercase : Dict=99 , _lowercase : Any=32 , _lowercase : Dict=2 , _lowercase : int=4 , _lowercase : str=37 , _lowercase : Optional[int]="gelu" , _lowercase : int=0.1 , _lowercase : List[Any]=0.1 , _lowercase : Tuple=5_12 , _lowercase : str=16 , _lowercase : List[str]=2 , _lowercase : List[str]=0.02 , _lowercase : List[Any]=3 , _lowercase : Tuple=4 , _lowercase : Dict=None , ): __UpperCAmelCase = parent __UpperCAmelCase = 13 __UpperCAmelCase = 7 __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = 99 __UpperCAmelCase = 3_84 __UpperCAmelCase = 2 __UpperCAmelCase = 4 __UpperCAmelCase = 37 __UpperCAmelCase = '''gelu''' __UpperCAmelCase = 0.1 __UpperCAmelCase = 0.1 __UpperCAmelCase = 5_12 __UpperCAmelCase = 16 __UpperCAmelCase = 2 __UpperCAmelCase = 0.02 __UpperCAmelCase = 3 __UpperCAmelCase = 4 __UpperCAmelCase = 1_28 __UpperCAmelCase = 2 __UpperCAmelCase = 9 __UpperCAmelCase = 1 __UpperCAmelCase = None def a ( self : List[str] ): __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase = None if self.use_input_mask: __UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase = None if self.use_token_type_ids: __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase = None __UpperCAmelCase = None __UpperCAmelCase = None if self.use_labels: __UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase = 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=_lowercase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a ( self : str , _lowercase : Union[str, Any] , _lowercase : Dict , _lowercase : List[str] , _lowercase : List[Any] , _lowercase : int , _lowercase : Dict , _lowercase : Any ): __UpperCAmelCase = TFConvBertModel(config=_lowercase ) __UpperCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __UpperCAmelCase = [input_ids, input_mask] __UpperCAmelCase = model(_lowercase ) __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : str , _lowercase : Tuple , _lowercase : List[Any] , _lowercase : Any , _lowercase : str , _lowercase : Optional[int] , _lowercase : str , _lowercase : Dict ): __UpperCAmelCase = TFConvBertForMaskedLM(config=_lowercase ) __UpperCAmelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a ( self : Optional[int] , _lowercase : List[str] , _lowercase : Any , _lowercase : List[Any] , _lowercase : Tuple , _lowercase : Dict , _lowercase : List[Any] , _lowercase : List[Any] ): __UpperCAmelCase = self.num_labels __UpperCAmelCase = TFConvBertForSequenceClassification(config=_lowercase ) __UpperCAmelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a ( self : List[Any] , _lowercase : Optional[Any] , _lowercase : int , _lowercase : List[Any] , _lowercase : int , _lowercase : int , _lowercase : Any , _lowercase : List[str] ): __UpperCAmelCase = self.num_choices __UpperCAmelCase = TFConvBertForMultipleChoice(config=_lowercase ) __UpperCAmelCase = tf.tile(tf.expand_dims(_lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCAmelCase = tf.tile(tf.expand_dims(_lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCAmelCase = tf.tile(tf.expand_dims(_lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCAmelCase = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a ( self : List[Any] , _lowercase : Tuple , _lowercase : Any , _lowercase : List[str] , _lowercase : str , _lowercase : Dict , _lowercase : Dict , _lowercase : str ): __UpperCAmelCase = self.num_labels __UpperCAmelCase = TFConvBertForTokenClassification(config=_lowercase ) __UpperCAmelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a ( self : Optional[int] , _lowercase : Any , _lowercase : Any , _lowercase : Any , _lowercase : Optional[Any] , _lowercase : Tuple , _lowercase : List[Any] , _lowercase : Any ): __UpperCAmelCase = TFConvBertForQuestionAnswering(config=_lowercase ) __UpperCAmelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __UpperCAmelCase = model(_lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a ( self : str ): __UpperCAmelCase = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) = config_and_inputs __UpperCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class _UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): a__ : Tuple = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a__ : List[str] = ( { "feature-extraction": TFConvBertModel, "fill-mask": TFConvBertForMaskedLM, "question-answering": TFConvBertForQuestionAnswering, "text-classification": TFConvBertForSequenceClassification, "token-classification": TFConvBertForTokenClassification, "zero-shot": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a__ : int = False a__ : List[str] = False a__ : Dict = False def a ( self : Optional[Any] ): __UpperCAmelCase = TFConvBertModelTester(self ) __UpperCAmelCase = ConfigTester(self , config_class=_lowercase , hidden_size=37 ) def a ( self : Union[str, Any] ): self.config_tester.run_common_tests() def a ( self : Any ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def a ( self : Dict ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowercase ) def a ( self : Union[str, Any] ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowercase ) def a ( self : Union[str, Any] ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowercase ) def a ( self : Any ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowercase ) def a ( self : Any ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowercase ) @slow def a ( self : Tuple ): __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase = True __UpperCAmelCase = True if hasattr(_lowercase , '''use_cache''' ): __UpperCAmelCase = True __UpperCAmelCase = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __UpperCAmelCase = getattr(self.model_tester , '''key_length''' , _lowercase ) for model_class in self.all_model_classes: __UpperCAmelCase = self._prepare_for_class(_lowercase , _lowercase ) __UpperCAmelCase = model_class(_lowercase ) __UpperCAmelCase = len(model(_lowercase ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_lowercase , saved_model=_lowercase ) __UpperCAmelCase = os.path.join(_lowercase , '''saved_model''' , '''1''' ) __UpperCAmelCase = tf.keras.models.load_model(_lowercase ) __UpperCAmelCase = model(_lowercase ) if self.is_encoder_decoder: __UpperCAmelCase = outputs['''encoder_hidden_states'''] __UpperCAmelCase = outputs['''encoder_attentions'''] else: __UpperCAmelCase = outputs['''hidden_states'''] __UpperCAmelCase = outputs['''attentions'''] self.assertEqual(len(_lowercase ) , _lowercase ) __UpperCAmelCase = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_lowercase ) , 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 a ( self : Tuple ): __UpperCAmelCase = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) self.assertIsNotNone(_lowercase ) def a ( self : Optional[Any] ): __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase = True __UpperCAmelCase = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length ) __UpperCAmelCase = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __UpperCAmelCase = getattr(self.model_tester , '''key_length''' , _lowercase ) __UpperCAmelCase = getattr(self.model_tester , '''key_length''' , _lowercase ) def check_decoder_attentions_output(_lowercase : Any ): __UpperCAmelCase = len(_lowercase ) self.assertEqual(out_len % 2 , 0 ) __UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(_lowercase ) , 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(_lowercase : Tuple ): __UpperCAmelCase = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_lowercase ) , 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: __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = model_class(_lowercase ) __UpperCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) __UpperCAmelCase = len(_lowercase ) self.assertEqual(config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) if self.is_encoder_decoder: __UpperCAmelCase = model_class(_lowercase ) __UpperCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(config.output_hidden_states , _lowercase ) check_decoder_attentions_output(_lowercase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __UpperCAmelCase = True __UpperCAmelCase = model_class(_lowercase ) __UpperCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) # Check attention is always last and order is fine __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = model_class(_lowercase ) __UpperCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_lowercase ) ) self.assertEqual(model.config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) @require_tf class _UpperCAmelCase ( unittest.TestCase ): @slow def a ( self : Tuple ): __UpperCAmelCase = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) __UpperCAmelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCAmelCase = model(_lowercase )[0] __UpperCAmelCase = [1, 6, 7_68] self.assertEqual(output.shape , _lowercase ) __UpperCAmelCase = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _lowercase , atol=1E-4 )
49
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int SCREAMING_SNAKE_CASE__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _UpperCamelCase( datasets.BuilderConfig ): __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None def UpperCAmelCase__ ( lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[int] , ): import pyspark def generate_fn(): __a : List[Any] = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __a : Optional[int] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __a : Optional[Any] = partition_df.collect() __a : Union[str, Any] = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _UpperCamelCase( _BaseExamplesIterable ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : Dict=None , ): '''simple docstring''' __a : List[str] = df __a : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) __a : List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.random.Generator ): '''simple docstring''' __a : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return len(self.partition_order ) class _UpperCamelCase( datasets.DatasetBuilder ): __SCREAMING_SNAKE_CASE : List[str] = SparkConfig def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' import pyspark __a : int = pyspark.sql.SparkSession.builder.getOrCreate() __a : Optional[int] = df __a : List[Any] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__ : List[str] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE__ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __a : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE__ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE__ : int ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __a : List[str] = self.df.count() __a : Dict = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __a : List[str] = ( self.df.limit(SCREAMING_SNAKE_CASE__ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE__ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __a : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __a : Union[str, Any] = min(SCREAMING_SNAKE_CASE__ , int(approx_total_size / max_shard_size ) ) __a : int = self.df.repartition(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , ): '''simple docstring''' import pyspark __a : Any = ParquetWriter if file_format == 'parquet' else ArrowWriter __a : Union[str, Any] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) if self._working_dir else fpath __a : Optional[int] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __a : List[str] = self.config.features __a : int = self._writer_batch_size __a : Union[str, Any] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __a : Any = pyspark.TaskContext().taskAttemptId() __a : str = next(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __a : Any = 0 __a : List[str] = writer_class( features=SCREAMING_SNAKE_CASE__ , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __a , __a : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __a : Optional[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Union[str, Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) if writer._num_bytes > 0: __a , __a : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ): __a : Any = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ) , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) shutil.move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE__ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , SCREAMING_SNAKE_CASE__ : str = "arrow" , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' self._validate_cache_dir() __a : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = not is_remote_filesystem(self._fs ) __a : Optional[Any] = os.path.join if is_local else posixpath.join __a : Any = '-TTTTT-SSSSS-of-NNNNN' __a : Union[str, Any] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __a : Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE__ ) __a : Any = 0 __a : Dict = 0 __a : int = 0 __a : List[str] = [] __a : Optional[int] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE__ ) __a : List[str] = total_num_examples __a : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __a : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __a : Dict = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): rename( SCREAMING_SNAKE_CASE__ , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __a : Union[str, Any] = [] __a : List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a , __a : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE__ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ).map(lambda SCREAMING_SNAKE_CASE__ : _rename_shard(*SCREAMING_SNAKE_CASE__ ) ).collect() else: # don't use any pattern __a : List[Any] = 0 __a : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE__ , '' ) , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
47
0
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def A__ ( __lowerCAmelCase : dict ): return (data["data"], data["target"]) def A__ ( __lowerCAmelCase : np.ndarray , __lowerCAmelCase : np.ndarray , __lowerCAmelCase : np.ndarray ): lowerCamelCase__ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(__lowerCAmelCase , __lowerCAmelCase ) # Predict target for test data lowerCamelCase__ = xgb.predict(__lowerCAmelCase ) lowerCamelCase__ = predictions.reshape(len(__lowerCAmelCase ) , 1 ) return predictions def A__ ( ): lowerCamelCase__ = fetch_california_housing() lowerCamelCase__ , lowerCamelCase__ = data_handling(__lowerCAmelCase ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = train_test_split( __lowerCAmelCase , __lowerCAmelCase , test_size=0.25 , random_state=1 ) lowerCamelCase__ = xgboost(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Error printing print(F'''Mean Absolute Error : {mean_absolute_error(__lowerCAmelCase , __lowerCAmelCase )}''' ) print(F'''Mean Square Error : {mean_squared_error(__lowerCAmelCase , __lowerCAmelCase )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
50
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : int ): # save results if os.path.exists(lowerCamelCase_ ): if os.path.exists(os.path.join(lowerCamelCase_ , 'config.json' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'config.json' ) ): os.remove(os.path.join(lowerCamelCase_ , 'config.json' ) ) if os.path.exists(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ): os.remove(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) else: os.makedirs(lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : Any=False ): __a : Dict = 2 if unlogit: __a : Optional[Any] = torch.pow(lowerCamelCase_ , lowerCamelCase_ ) __a : Any = p * torch.log(lowerCamelCase_ ) __a : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ ( lowerCamelCase_ : Any ): logger.info('lv, h >\t' + '\t'.join(f'''{x + 1}''' for x in range(len(lowerCamelCase_ ) ) ) ) for row in range(len(lowerCamelCase_ ) ): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:d}''' for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=False ): __a , __a : Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads __a : str = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) __a : int = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) if head_mask is None: __a : Union[str, Any] = torch.ones(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCamelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __a : Any = None __a : Optional[int] = 0.0 __a : Optional[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCamelCase_ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __a : Dict = tuple(t.to(args.device ) for t in inputs ) ((__a) , ) : Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __a : List[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ , head_mask=lowerCamelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __a , __a , __a : int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCamelCase_ ): __a : List[str] = entropy(attn.detach() , lowerCamelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCamelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __a : Optional[Any] = 2 __a : Union[str, Any] = torch.pow(torch.pow(lowerCamelCase_ , lowerCamelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: __a : List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(lowerCamelCase_ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(lowerCamelCase_ ) logger.info('Head ranked by importance scores' ) __a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __a : str = torch.arange( head_importance.numel() , device=args.device ) __a : Tuple = head_ranks.view_as(lowerCamelCase_ ) print_ad_tensor(lowerCamelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): __a , __a , __a : Optional[int] = compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ ) __a : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , lowerCamelCase_ , original_score * args.masking_threshold ) __a : Tuple = torch.ones_like(lowerCamelCase_ ) __a : int = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __a : Tuple = original_score while current_score >= original_score * args.masking_threshold: __a : Optional[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __a : List[str] = float('Inf' ) __a : List[Any] = head_importance.view(-1 ).sort()[1] if len(lowerCamelCase_ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __a : Any = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __a : int = new_head_mask.view(-1 ) __a : Tuple = 0.0 __a : int = new_head_mask.view_as(lowerCamelCase_ ) __a : Optional[int] = new_head_mask.clone().detach() print_ad_tensor(lowerCamelCase_ ) # Compute metric and head importance again __a , __a , __a : int = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[Any] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowerCamelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(lowerCamelCase_ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): __a : List[Any] = datetime.now() __a , __a , __a : List[str] = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[str] = 1 / loss __a : List[Any] = datetime.now() - before_time __a : List[str] = sum(p.numel() for p in model.parameters() ) __a : Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __a : Tuple = [ v, ] assert sum(len(lowerCamelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCamelCase_ ) __a : Optional[Any] = sum(p.numel() for p in model.parameters() ) __a : Tuple = datetime.now() __a , __a , __a : Tuple = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ , actually_pruned=lowerCamelCase_ , ) __a : Optional[Any] = 1 / loss __a : List[Any] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowerCamelCase_ , lowerCamelCase_ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , lowerCamelCase_ , lowerCamelCase_ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(lowerCamelCase_ , args.output_dir ) def UpperCAmelCase__ ( ): __a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=lowerCamelCase_ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=lowerCamelCase_ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=lowerCamelCase_ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=lowerCamelCase_ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=lowerCamelCase_ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=lowerCamelCase_ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=lowerCamelCase_ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=lowerCamelCase_ , help='Batch size.' ) parser.add_argument('--seed' , type=lowerCamelCase_ , default=4_2 ) parser.add_argument('--local_rank' , type=lowerCamelCase_ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) __a : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCamelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __a : List[str] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __a : Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __a : Union[str, Any] = torch.device('cuda' , args.local_rank ) __a : Any = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __a : Optional[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __a : List[Any] = nn.parallel.DistributedDataParallel( lowerCamelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCamelCase_ ) elif args.n_gpu > 1: __a : Union[str, Any] = nn.DataParallel(lowerCamelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , lowerCamelCase_ ) # Prepare dataset __a : Tuple = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __a : str = (torch.from_numpy(lowerCamelCase_ ),) __a : List[str] = TensorDataset(*lowerCamelCase_ ) __a : Optional[Any] = RandomSampler(lowerCamelCase_ ) __a : Union[str, Any] = DataLoader(lowerCamelCase_ , sampler=lowerCamelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __a : Union[str, Any] = mask_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) prune_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
47
0
'''simple docstring''' import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version a__ : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt') def __snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : int = 16_000 ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = int(round(sample_rate * max_length ) ) if len(SCREAMING_SNAKE_CASE_ ) <= sample_length: return wav UpperCAmelCase = randint(0 , len(SCREAMING_SNAKE_CASE_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field(default=UpperCAmelCase_ , metadata={"help": "Name of a dataset from the datasets package"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "A file containing the training audio paths and labels."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "A file containing the validation audio paths and labels."} ) _lowerCamelCase =field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) _lowerCamelCase =field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) _lowerCamelCase =field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) _lowerCamelCase =field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) _lowerCamelCase =field( default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) _lowerCamelCase =field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Name or path of preprocessor config."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def __snake_case ( self : Union[str, Any] ): if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , a__ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def __snake_case ( ) -> int: """simple docstring""" UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCAmelCase = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE_ ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} " + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. UpperCAmelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. UpperCAmelCase = DatasetDict() UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--label_column_name` to the correct text column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy UpperCAmelCase = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. UpperCAmelCase = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) UpperCAmelCase = feature_extractor.model_input_names[0] def train_transforms(SCREAMING_SNAKE_CASE_ : int ): UpperCAmelCase = [] for audio in batch[data_args.audio_column_name]: UpperCAmelCase = random_subsample( audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(SCREAMING_SNAKE_CASE_ : List[Any] ): UpperCAmelCase = [audio['''array'''] for audio in batch[data_args.audio_column_name]] UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. UpperCAmelCase = raw_datasets['''train'''].features[data_args.label_column_name].names UpperCAmelCase, UpperCAmelCase = {}, {} for i, label in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase = str(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = label # Load the accuracy metric from the datasets package UpperCAmelCase = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(SCREAMING_SNAKE_CASE_ : Dict ): UpperCAmelCase = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=SCREAMING_SNAKE_CASE_ , references=eval_pred.label_ids ) UpperCAmelCase = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(SCREAMING_SNAKE_CASE_ ) , labelaid=SCREAMING_SNAKE_CASE_ , idalabel=SCREAMING_SNAKE_CASE_ , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: UpperCAmelCase = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(SCREAMING_SNAKE_CASE_ , output_all_columns=SCREAMING_SNAKE_CASE_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: UpperCAmelCase = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(SCREAMING_SNAKE_CASE_ , output_all_columns=SCREAMING_SNAKE_CASE_ ) # Initialize our trainer UpperCAmelCase = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: UpperCAmelCase = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase = last_checkpoint UpperCAmelCase = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCAmelCase = trainer.evaluate() trainer.log_metrics('''eval''' , SCREAMING_SNAKE_CASE_ ) trainer.save_metrics('''eval''' , SCREAMING_SNAKE_CASE_ ) # Write model card and (optionally) push to hub UpperCAmelCase = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE_ ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
51
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __a : List[Any] = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1_0_2_4, 'hidden_size': 7_6_8, 'max_length': 5_1_2, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1_0_2_4, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __a : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a : List[str] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a : int = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __a : Optional[Any] = os.path.join(get_home_dir() , 'models' ) __a : Optional[Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __a : Any = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __a : Dict = original_bort._collect_params_with_prefix() # Build our config 🤗 __a : Optional[Any] = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(lowerCamelCase_ ), } __a : str = BertConfig.from_dict(lowerCamelCase_ ) __a : Optional[int] = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Optional[Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __a : Optional[int] = hf_param.shape __a : int = to_torch(params[gluon_param] ) __a : int = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __a : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __a : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __a : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __a : BertSelfAttention = layer.attention.self __a : Optional[int] = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a : str = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a : str = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a : Dict = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a : str = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a : BertSelfOutput = layer.attention.output __a : Tuple = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a : Dict = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a : BertIntermediate = layer.intermediate __a : List[str] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a : Optional[Any] = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a : BertOutput = layer.output __a : str = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a : List[Any] = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a : List[str] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a : Union[str, Any] = RobertaTokenizer.from_pretrained('roberta-base' ) __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ )['input_ids'] # Get gluon output __a : Optional[int] = mx.nd.array([input_ids] ) __a : Tuple = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __a : Optional[Any] = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ , return_tensors='pt' ) __a : int = hf_bort_model(**lowerCamelCase_ )[0] __a : Dict = output_gluon[0].asnumpy() __a : str = output_hf[0].detach().numpy() __a : List[Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a : str = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
47
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input A = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def __A ( ) -> str: __a : Dict = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __a : Union[str, Any] = get_sagemaker_input() else: __a : Tuple = get_cluster_input() return config def __A ( a_ :str=None) -> str: if subparsers is not None: __a : int = subparsers.add_parser('''config''' , description=a_) else: __a : Optional[Any] = argparse.ArgumentParser('''Accelerate config command''' , description=a_) parser.add_argument( '''--config_file''' , default=a_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=a_) return parser def __A ( a_ :Tuple) -> Any: __a : List[Any] = get_user_input() if args.config_file is not None: __a : str = args.config_file else: if not os.path.isdir(a_): os.makedirs(a_) __a : Any = default_yaml_config_file if config_file.endswith('''.json'''): config.to_json_file(a_) else: config.to_yaml_file(a_) print(F"""accelerate configuration saved at {config_file}""") def __A ( ) -> int: __a : int = config_command_parser() __a : List[Any] = parser.parse_args() config_command(a_) if __name__ == "__main__": main()
52
def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ): __a : Any = '' for i in table: res += inp[i - 1] return res def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] ): return data[1:] + data[0] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): __a : Optional[int] = '' for i in range(len(lowerCamelCase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): __a : List[str] = int('0b' + data[0] + data[-1] , 2 ) __a : List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = message[:4] __a : str = message[4:] __a : Any = apply_table(lowerCamelCase_ , lowerCamelCase_ ) __a : int = xor(lowerCamelCase_ , lowerCamelCase_ ) __a : Dict = apply_sbox(lowerCamelCase_ , temp[:4] ) # noqa: E741 __a : Tuple = apply_sbox(lowerCamelCase_ , temp[4:] ) __a : List[Any] = '0' * (2 - len(lowerCamelCase_ )) + l # noqa: E741 __a : List[str] = '0' * (2 - len(lowerCamelCase_ )) + r __a : List[Any] = apply_table(l + r , lowerCamelCase_ ) __a : Dict = xor(lowerCamelCase_ , lowerCamelCase_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE__ = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE__ = [6, 3, 7, 4, 8, 5, 10, 9] SCREAMING_SNAKE_CASE__ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] SCREAMING_SNAKE_CASE__ = [2, 4, 3, 1] SCREAMING_SNAKE_CASE__ = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE__ = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE__ = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE__ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE__ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE__ = apply_table(key, paa_table) SCREAMING_SNAKE_CASE__ = temp[:5] SCREAMING_SNAKE_CASE__ = temp[5:] SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE__ = apply_table(message, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE__ = apply_table(CT, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
47
0
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _snake_case : Optional[int] = logging.get_logger(__name__) # General docstring _snake_case : int = 'RegNetConfig' # Base docstring _snake_case : List[str] = 'facebook/regnet-y-040' _snake_case : List[Any] = [1, 1088, 7, 7] # Image classification docstring _snake_case : List[Any] = 'facebook/regnet-y-040' _snake_case : Union[str, Any] = 'tabby, tabby cat' _snake_case : str = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : List[str] , lowerCAmelCase_ : int , lowerCAmelCase_ : int = 3 , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : Optional[str] = "relu" , **lowerCAmelCase_ : Any , ) -> Tuple: super().__init__(**lowerCAmelCase_ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCAmelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __lowerCAmelCase = tf.keras.layers.ConvaD( filters=lowerCAmelCase_ , kernel_size=lowerCAmelCase_ , strides=lowerCAmelCase_ , padding='VALID' , groups=lowerCAmelCase_ , use_bias=lowerCAmelCase_ , name='convolution' , ) __lowerCAmelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) __lowerCAmelCase = ACTaFN[activation] if activation is not None else tf.identity def lowercase ( self : Optional[Any] , lowerCAmelCase_ : List[str] ) -> Any: __lowerCAmelCase = self.convolution(self.padding(lowerCAmelCase_ ) ) __lowerCAmelCase = self.normalization(lowerCAmelCase_ ) __lowerCAmelCase = self.activation(lowerCAmelCase_ ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase_ : RegNetConfig , **lowerCAmelCase_ : Optional[Any] ) -> List[Any]: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = config.num_channels __lowerCAmelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='embedder' , ) def lowercase ( self : Optional[int] , lowerCAmelCase_ : Optional[Any] ) -> List[Any]: __lowerCAmelCase = shape_list(lowerCAmelCase_ )[1] if tf.executing_eagerly() and 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.' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCAmelCase = tf.transpose(lowerCAmelCase_ , perm=(0, 2, 3, 1) ) __lowerCAmelCase = self.embedder(lowerCAmelCase_ ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : int = 2 , **lowerCAmelCase_ : Tuple ) -> List[str]: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = tf.keras.layers.ConvaD( filters=lowerCAmelCase_ , kernel_size=1 , strides=lowerCAmelCase_ , use_bias=lowerCAmelCase_ , name='convolution' ) __lowerCAmelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) def lowercase ( self : List[Any] , lowerCAmelCase_ : tf.Tensor , lowerCAmelCase_ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(lowerCAmelCase_ ) , training=lowerCAmelCase_ ) class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : str , lowerCAmelCase_ : int , lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ) -> str: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase_ , name='pooler' ) __lowerCAmelCase = [ tf.keras.layers.ConvaD(filters=lowerCAmelCase_ , kernel_size=1 , activation='relu' , name='attention.0' ), tf.keras.layers.ConvaD(filters=lowerCAmelCase_ , kernel_size=1 , activation='sigmoid' , name='attention.2' ), ] def lowercase ( self : Optional[int] , lowerCAmelCase_ : List[str] ) -> Optional[int]: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCAmelCase = self.pooler(lowerCAmelCase_ ) for layer_module in self.attention: __lowerCAmelCase = layer_module(lowerCAmelCase_ ) __lowerCAmelCase = hidden_state * pooled return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase_ : RegNetConfig , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int = 1 , **lowerCAmelCase_ : Optional[int] ) -> List[str]: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = in_channels != out_channels or stride != 1 __lowerCAmelCase = max(1 , out_channels // config.groups_width ) __lowerCAmelCase = ( TFRegNetShortCut(lowerCAmelCase_ , stride=lowerCAmelCase_ , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCAmelCase = [ TFRegNetConvLayer(lowerCAmelCase_ , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( lowerCAmelCase_ , stride=lowerCAmelCase_ , groups=lowerCAmelCase_ , activation=config.hidden_act , name='layer.1' ), TFRegNetConvLayer(lowerCAmelCase_ , kernel_size=1 , activation=lowerCAmelCase_ , name='layer.2' ), ] __lowerCAmelCase = ACTaFN[config.hidden_act] def lowercase ( self : List[str] , lowerCAmelCase_ : str ) -> Union[str, Any]: __lowerCAmelCase = hidden_state for layer_module in self.layers: __lowerCAmelCase = layer_module(lowerCAmelCase_ ) __lowerCAmelCase = self.shortcut(lowerCAmelCase_ ) hidden_state += residual __lowerCAmelCase = self.activation(lowerCAmelCase_ ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Optional[Any] , lowerCAmelCase_ : RegNetConfig , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int = 1 , **lowerCAmelCase_ : List[str] ) -> str: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = in_channels != out_channels or stride != 1 __lowerCAmelCase = max(1 , out_channels // config.groups_width ) __lowerCAmelCase = ( TFRegNetShortCut(lowerCAmelCase_ , stride=lowerCAmelCase_ , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) __lowerCAmelCase = [ TFRegNetConvLayer(lowerCAmelCase_ , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( lowerCAmelCase_ , stride=lowerCAmelCase_ , groups=lowerCAmelCase_ , activation=config.hidden_act , name='layer.1' ), TFRegNetSELayer(lowerCAmelCase_ , reduced_channels=int(round(in_channels / 4 ) ) , name='layer.2' ), TFRegNetConvLayer(lowerCAmelCase_ , kernel_size=1 , activation=lowerCAmelCase_ , name='layer.3' ), ] __lowerCAmelCase = ACTaFN[config.hidden_act] def lowercase ( self : Tuple , lowerCAmelCase_ : Optional[Any] ) -> Union[str, Any]: __lowerCAmelCase = hidden_state for layer_module in self.layers: __lowerCAmelCase = layer_module(lowerCAmelCase_ ) __lowerCAmelCase = self.shortcut(lowerCAmelCase_ ) hidden_state += residual __lowerCAmelCase = self.activation(lowerCAmelCase_ ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Any , lowerCAmelCase_ : RegNetConfig , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int = 2 , lowerCAmelCase_ : int = 2 , **lowerCAmelCase_ : Optional[int] ) -> Optional[Any]: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCAmelCase = [ # downsampling is done in the first layer with stride of 2 layer(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , stride=lowerCAmelCase_ , name='layers.0' ), *[layer(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def lowercase ( self : int , lowerCAmelCase_ : int ) -> str: for layer_module in self.layers: __lowerCAmelCase = layer_module(lowerCAmelCase_ ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase_ : RegNetConfig , **lowerCAmelCase_ : str ) -> List[str]: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( lowerCAmelCase_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='stages.0' , ) ) __lowerCAmelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(lowerCAmelCase_ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , depth=lowerCAmelCase_ , name=f"""stages.{i+1}""" ) ) def lowercase ( self : Any , lowerCAmelCase_ : tf.Tensor , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True ) -> TFBaseModelOutputWithNoAttention: __lowerCAmelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCAmelCase = hidden_states + (hidden_state,) __lowerCAmelCase = stage_module(lowerCAmelCase_ ) if output_hidden_states: __lowerCAmelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase_ , hidden_states=lowerCAmelCase_ ) @keras_serializable class _UpperCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" a_ = RegNetConfig def __init__( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Optional[Any] ) -> str: super().__init__(**lowerCAmelCase_ ) __lowerCAmelCase = config __lowerCAmelCase = TFRegNetEmbeddings(lowerCAmelCase_ , name='embedder' ) __lowerCAmelCase = TFRegNetEncoder(lowerCAmelCase_ , name='encoder' ) __lowerCAmelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase_ , name='pooler' ) @unpack_inputs def lowercase ( self : str , lowerCAmelCase_ : tf.Tensor , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __lowerCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict __lowerCAmelCase = self.embedder(lowerCAmelCase_ , training=lowerCAmelCase_ ) __lowerCAmelCase = self.encoder( lowerCAmelCase_ , output_hidden_states=lowerCAmelCase_ , return_dict=lowerCAmelCase_ , training=lowerCAmelCase_ ) __lowerCAmelCase = encoder_outputs[0] __lowerCAmelCase = self.pooler(lowerCAmelCase_ ) # Change to NCHW output format have uniformity in the modules __lowerCAmelCase = tf.transpose(lowerCAmelCase_ , perm=(0, 3, 1, 2) ) __lowerCAmelCase = tf.transpose(lowerCAmelCase_ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCAmelCase = tuple([tf.transpose(lowerCAmelCase_ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowerCAmelCase_ , pooler_output=lowerCAmelCase_ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = RegNetConfig a_ = """regnet""" a_ = """pixel_values""" @property def lowercase ( self : Tuple ) -> List[str]: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} _snake_case : List[str] = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' _snake_case : Union[str, Any] = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""" , _UpperCamelCase , ) class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase_ : RegNetConfig , *lowerCAmelCase_ : Tuple , **lowerCAmelCase_ : List[str] ) -> int: super().__init__(lowerCAmelCase_ , *lowerCAmelCase_ , **lowerCAmelCase_ ) __lowerCAmelCase = TFRegNetMainLayer(lowerCAmelCase_ , name='regnet' ) @unpack_inputs @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 lowercase ( self : int , lowerCAmelCase_ : tf.Tensor , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : List[Any]=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __lowerCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict __lowerCAmelCase = self.regnet( pixel_values=lowerCAmelCase_ , output_hidden_states=lowerCAmelCase_ , return_dict=lowerCAmelCase_ , training=lowerCAmelCase_ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , _UpperCamelCase , ) class _UpperCAmelCase ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" def __init__( self : str , lowerCAmelCase_ : RegNetConfig , *lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Tuple ) -> Dict: super().__init__(lowerCAmelCase_ , *lowerCAmelCase_ , **lowerCAmelCase_ ) __lowerCAmelCase = config.num_labels __lowerCAmelCase = TFRegNetMainLayer(lowerCAmelCase_ , name='regnet' ) # classification head __lowerCAmelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='classifier.1' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @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 lowercase ( self : Optional[int] , lowerCAmelCase_ : tf.Tensor = None , lowerCAmelCase_ : tf.Tensor = None , lowerCAmelCase_ : bool = None , lowerCAmelCase_ : bool = None , lowerCAmelCase_ : str=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __lowerCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict __lowerCAmelCase = self.regnet( lowerCAmelCase_ , output_hidden_states=lowerCAmelCase_ , return_dict=lowerCAmelCase_ , training=lowerCAmelCase_ ) __lowerCAmelCase = outputs.pooler_output if return_dict else outputs[1] __lowerCAmelCase = self.classifier[0](lowerCAmelCase_ ) __lowerCAmelCase = self.classifier[1](lowerCAmelCase_ ) __lowerCAmelCase = None if labels is None else self.hf_compute_loss(labels=lowerCAmelCase_ , logits=lowerCAmelCase_ ) if not return_dict: __lowerCAmelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=lowerCAmelCase_ , logits=lowerCAmelCase_ , hidden_states=outputs.hidden_states )
53
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=__lowercase ) class A ( __lowercase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _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 lowerCAmelCase__ ( self: List[Any] ) -> Dict[str, str]: '''simple docstring''' return {self.text_column: "text", self.summary_column: "summary"}
54
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''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 _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''roberta''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : str=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = vocab_size __a : Tuple = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : str = hidden_act __a : Optional[Any] = intermediate_size __a : Dict = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Dict = type_vocab_size __a : str = initializer_range __a : List[str] = layer_norm_eps __a : Optional[int] = position_embedding_type __a : Union[str, Any] = use_cache __a : str = classifier_dropout class _UpperCamelCase( __lowerCamelCase ): @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' if self.task == "multiple-choice": __a : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
0
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[Any] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Any ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Any ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) @require_torch def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = [torch.ones((1, 3, 5, 5) )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks(A ,A ,A ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = processor.post_process_masks( A ,torch.tensor(A ) ,torch.tensor(A ) ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) # should also work with np __A = [np.ones((1, 3, 5, 5) )] __A = processor.post_process_masks(A ,np.array(A ) ,np.array(A ) ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = [[1, 0], [0, 1]] with self.assertRaises(A ): __A = processor.post_process_masks(A ,np.array(A ) ,np.array(A ) ) @require_vision @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Tuple ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : int ): __A = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) @require_tf def UpperCamelCase_ ( self : Dict ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = [tf.ones((1, 3, 5, 5) )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks(A ,A ,A ,return_tensors="tf" ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = processor.post_process_masks( A ,tf.convert_to_tensor(A ) ,tf.convert_to_tensor(A ) ,return_tensors="tf" ,) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) # should also work with np __A = [np.ones((1, 3, 5, 5) )] __A = processor.post_process_masks( A ,np.array(A ) ,np.array(A ) ,return_tensors="tf" ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __A = processor.post_process_masks( A ,np.array(A ) ,np.array(A ) ,return_tensors="tf" ) @require_vision @require_torchvision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[int] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : str ,**A : str ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Optional[Any] ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = np.random.randint(0 ,2 ,size=(1, 3, 5, 5) ).astype(np.floataa ) __A = [tf.convert_to_tensor(A )] __A = [torch.tensor(A )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks( A ,A ,A ,return_tensors="tf" ) __A = processor.post_process_masks( A ,A ,A ,return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def UpperCamelCase_ ( self : List[str] ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="pt" )["pixel_values"].numpy() __A = processor(images=A ,return_tensors="pt" )["pixel_values"].numpy() __A = image_processor(A ,return_tensors="tf" )["pixel_values"].numpy() __A = processor(images=A ,return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(A ,A ) ) self.assertTrue(np.allclose(A ,A ) ) self.assertTrue(np.allclose(A ,A ) )
55
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''▁''' SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } SCREAMING_SNAKE_CASE__ = { '''facebook/xglm-564M''': 2048, } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="<unk>" , SCREAMING_SNAKE_CASE__ : Dict="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer __a : Any = 7 __a : Union[str, Any] = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words )] __a : Union[str, Any] = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) __a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Any = 1 # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __a : List[str] = len(self.sp_model ) __a : Optional[int] = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) __a : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[str] ): '''simple docstring''' __a : Tuple = self.__dict__.copy() __a : List[str] = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Dict = {} __a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a __a : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _lowercase ( __lowercase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : str = TextToVideoSDPipeline _SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. _SCREAMING_SNAKE_CASE : List[str] = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : Union[str, Any] ) -> Dict: torch.manual_seed(0 ) __snake_case = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=32 , attention_head_dim=4 , ) __snake_case = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) __snake_case = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __snake_case = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __snake_case = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) __snake_case = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __snake_case = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def a ( self : Any , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0 ) -> Union[str, Any]: if str(SCREAMING_SNAKE_CASE_ ).startswith('mps' ): __snake_case = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: __snake_case = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) __snake_case = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def a ( self : Any ) -> Union[str, Any]: __snake_case = 'cpu' # ensure determinism for the device-dependent torch.Generator __snake_case = self.get_dummy_components() __snake_case = TextToVideoSDPipeline(**SCREAMING_SNAKE_CASE_ ) __snake_case = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) __snake_case = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) __snake_case = 'np' __snake_case = sd_pipe(**SCREAMING_SNAKE_CASE_ ).frames __snake_case = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) __snake_case = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def a ( self : Optional[int] ) -> str: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def a ( self : Any ) -> int: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ , expected_max_diff=1e-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def a ( self : List[str] ) -> Optional[int]: pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def a ( self : Optional[int] ) -> Any: pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def a ( self : List[Any] ) -> List[str]: pass def a ( self : Dict ) -> Optional[int]: return super().test_progress_bar() @slow @skip_mps class _lowercase ( unittest.TestCase ): def a ( self : List[Any] ) -> str: __snake_case = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) __snake_case = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) __snake_case = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __snake_case = pipe.to('cuda' ) __snake_case = 'Spiderman is surfing' __snake_case = torch.Generator(device='cpu' ).manual_seed(0 ) __snake_case = pipe(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=25 , output_type='pt' ).frames __snake_case = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def a ( self : Dict ) -> Any: __snake_case = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) __snake_case = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) __snake_case = pipe.to('cuda' ) __snake_case = 'Spiderman is surfing' __snake_case = torch.Generator(device='cpu' ).manual_seed(0 ) __snake_case = pipe(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , output_type='pt' ).frames __snake_case = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
56
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] SCREAMING_SNAKE_CASE__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] ): __a : str = torch.load(lowerCamelCase_ , map_location='cpu' ) return sd def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict=rename_keys_prefix ): __a : Optional[Any] = OrderedDict() __a : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a : List[Any] = key for name_pair in rename_keys_prefix: __a : List[str] = new_key.replace(name_pair[0] , name_pair[1] ) __a : Any = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a : int = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : Any ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a : Dict = 'pretraining' if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __a : int = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __a : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} __a : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __a : Any = {'visual_embedding_dim': 2_0_4_8} __a : List[str] = 'vqa_advanced' elif "vqa" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __a : List[Any] = 'vqa' elif "nlvr" in checkpoint_path: __a : Optional[int] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __a : Optional[Any] = 'nlvr' __a : str = VisualBertConfig(**lowerCamelCase_ ) # Load State Dict __a : str = load_state_dict(lowerCamelCase_ ) __a : str = get_new_dict(lowerCamelCase_ , lowerCamelCase_ ) if model_type == "pretraining": __a : Optional[Any] = VisualBertForPreTraining(lowerCamelCase_ ) elif model_type == "vqa": __a : Any = VisualBertForQuestionAnswering(lowerCamelCase_ ) elif model_type == "nlvr": __a : int = VisualBertForVisualReasoning(lowerCamelCase_ ) elif model_type == "multichoice": __a : Optional[int] = VisualBertForMultipleChoice(lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # Save Checkpoints Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
47
0
import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging A_ : Tuple = logging.get_logger(__name__) def snake_case () -> Optional[Any]: # Get the sagemaker specific mp parameters from smp_options variable. UpperCamelCase_: Optional[Any] = os.getenv('SM_HP_MP_PARAMETERS' , '{}' ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. UpperCamelCase_: List[str] = json.loads(UpperCAmelCase__ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. UpperCamelCase_: Any = os.getenv('SM_FRAMEWORK_PARAMS' , '{}' ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". UpperCamelCase_: Tuple = json.loads(UpperCAmelCase__ ) if not mpi_options.get('sagemaker_mpi_enabled' , UpperCAmelCase__ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec('smdistributed' ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : str =field( default='''''' , metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''} , ) def _a ( self ): super().__post_init__() warnings.warn( '`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use ' '`TrainingArguments` instead.' , _lowerCamelCase , ) @cached_property def _a ( self ): logger.info('PyTorch: setting up devices' ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( 'torch.distributed process group is initialized, but local_rank == -1. ' 'In order to use Torch DDP, launch your script with `python -m torch.distributed.launch' ) if self.no_cuda: UpperCamelCase_: str = torch.device('cpu' ) UpperCamelCase_: Optional[Any] = 0 elif is_sagemaker_model_parallel_available(): UpperCamelCase_: Optional[int] = smp.local_rank() UpperCamelCase_: Any = torch.device('cuda' , _lowerCamelCase ) UpperCamelCase_: int = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend='smddp' , timeout=self.ddp_timeout_delta ) UpperCamelCase_: Optional[int] = int(os.getenv('SMDATAPARALLEL_LOCAL_RANK' ) ) UpperCamelCase_: Dict = torch.device('cuda' , self.local_rank ) UpperCamelCase_: Union[str, Any] = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 UpperCamelCase_: Union[str, Any] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. UpperCamelCase_: Any = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend='nccl' , timeout=self.ddp_timeout_delta ) UpperCamelCase_: Optional[Any] = torch.device('cuda' , self.local_rank ) UpperCamelCase_: Optional[int] = 1 if device.type == "cuda": torch.cuda.set_device(_lowerCamelCase ) return device @property def _a ( self ): if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def _a ( self ): return not is_sagemaker_model_parallel_available() @property def _a ( self ): return False
57
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
47
0
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" _lowerCamelCase = IFPipeline _lowerCamelCase = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} _lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return self._get_dummy_components() def UpperCAmelCase__ ( self , _lowercase , _lowercase=0 ) -> List[str]: '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): snake_case_ : Optional[Any] = torch.manual_seed(_lowercase ) else: snake_case_ : int = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) snake_case_ : str = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' self._test_save_load_local() def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) snake_case_ : Optional[int] = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=_lowercase , tokenizer=_lowercase ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) snake_case_ , snake_case_ : int = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() snake_case_ : Union[str, Any] = None snake_case_ : int = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_lowercase , _lowercase , _lowercase , _lowercase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img snake_case_ : int = IFImgaImgPipeline(**pipe_a.components ) snake_case_ : int = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_lowercase , _lowercase , _lowercase , _lowercase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting snake_case_ : int = IFInpaintingPipeline(**pipe_a.components ) snake_case_ : List[str] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_lowercase , _lowercase , _lowercase , _lowercase ) def UpperCAmelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase ) -> List[str]: '''simple docstring''' _start_torch_memory_measurement() snake_case_ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : int = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , num_inference_steps=2 , generator=_lowercase , output_type="""np""" , ) snake_case_ : Dict = output.images[0] assert image.shape == (6_4, 6_4, 3) snake_case_ : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 1_3 * 1_0**9 snake_case_ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : str = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , image=_lowercase , generator=_lowercase , num_inference_steps=2 , output_type="""np""" , ) snake_case_ : Union[str, Any] = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) snake_case_ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 snake_case_ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) def UpperCAmelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase ) -> Any: '''simple docstring''' _start_torch_memory_measurement() snake_case_ : List[str] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : str = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : Union[str, Any] = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , image=_lowercase , num_inference_steps=2 , generator=_lowercase , output_type="""np""" , ) snake_case_ : List[str] = output.images[0] assert image.shape == (6_4, 6_4, 3) snake_case_ : str = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 snake_case_ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : Optional[int] = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : Union[str, Any] = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : Union[str, Any] = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , image=_lowercase , original_image=_lowercase , generator=_lowercase , num_inference_steps=2 , output_type="""np""" , ) snake_case_ : Optional[int] = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) snake_case_ : int = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 snake_case_ : str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) def UpperCAmelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase ) -> List[str]: '''simple docstring''' _start_torch_memory_measurement() snake_case_ : List[Any] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : List[str] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(1 ) ).to(_lowercase ) snake_case_ : Optional[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : int = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , image=_lowercase , mask_image=_lowercase , num_inference_steps=2 , generator=_lowercase , output_type="""np""" , ) snake_case_ : Any = output.images[0] assert image.shape == (6_4, 6_4, 3) snake_case_ : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 snake_case_ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : Optional[int] = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : Dict = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0 ) ).to(_lowercase ) snake_case_ : List[Any] = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(1 ) ).to(_lowercase ) snake_case_ : int = pipe_a( prompt_embeds=_lowercase , negative_prompt_embeds=_lowercase , image=_lowercase , mask_image=_lowercase , original_image=_lowercase , generator=_lowercase , num_inference_steps=2 , output_type="""np""" , ) snake_case_ : Dict = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) snake_case_ : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 snake_case_ : Optional[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_lowercase , _lowercase ) def __lowerCAmelCase ( ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
58
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class _UpperCamelCase( __lowerCamelCase ): def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[Any] = tempfile.mkdtemp() __a : int = 8 # DPR tok __a : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , 'dpr_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_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] ) ) # BART tok __a : str = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __a : Optional[int] = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __a : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : List[str] = {'unk_token': '<unk>'} __a : Dict = os.path.join(self.tmpdirname , 'bart_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['vocab_file'] ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowerCAmelCase ( self : str ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) ) def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Tuple = os.path.join(self.tmpdirname , 'rag_tokenizer' ) __a : Optional[Any] = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) __a : Optional[Any] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Optional[Any] = RagTokenizer.from_pretrained('facebook/rag-token-nq' ) __a : List[Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Any = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' ) __a : Union[str, Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : str = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
47
0
import numpy as np from transformers import Pipeline def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[Any] =np.max(__a , axis=-1 , keepdims=__a ) lowerCamelCase__: int =np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=__a ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Optional[int] , **UpperCAmelCase_ : Union[str, Any]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ={} if "second_text" in kwargs: lowerCamelCase__: Optional[int] =kwargs["second_text"] return preprocess_kwargs, {}, {} def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any]=None) ->int: '''simple docstring''' return self.tokenizer(UpperCAmelCase_ , text_pair=UpperCAmelCase_ , return_tensors=self.framework) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : int) ->int: '''simple docstring''' return self.model(**UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Optional[int]) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =model_outputs.logits[0].numpy() lowerCamelCase__: Any =softmax(UpperCAmelCase_) lowerCamelCase__: List[str] =np.argmax(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =self.model.config.idalabel[best_class] lowerCamelCase__: str =probabilities[best_class].item() lowerCamelCase__: List[str] =logits.tolist() return {"label": label, "score": score, "logits": logits}
59
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''spiece.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } SCREAMING_SNAKE_CASE__ = {'''bert_for_seq_generation''': 512} class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : int = ['''input_ids''', '''attention_mask'''] def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : Any="<unk>" , SCREAMING_SNAKE_CASE__ : int="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="<::::>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : int = vocab_file __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): '''simple docstring''' __a : Union[str, Any] = self.__dict__.copy() __a : Any = None return state def __setstate__( self : int , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' __a : str = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : str = {} __a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' __a : int = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Optional[Any] = [] __a : Optional[int] = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token __a : Dict = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Tuple = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_mobilebert''': [ '''MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileBertConfig''', '''MobileBertOnnxConfig''', ], '''tokenization_mobilebert''': ['''MobileBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''MobileBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''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: lowerCAmelCase_ = [ '''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 lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
from ..utils import DummyObject, requires_backends class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Any = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Dict , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] )
47
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Union[str, Any] ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() def a ( self : str ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = FlaxControlNetModel.from_pretrained( "lllyasviel/sd-controlnet-canny" , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa ) lowerCAmelCase__ , lowerCAmelCase__ = FlaxStableDiffusionControlNetPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , controlnet=SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa ) lowerCAmelCase__ = controlnet_params lowerCAmelCase__ = "bird" lowerCAmelCase__ = jax.device_count() lowerCAmelCase__ = pipe.prepare_text_inputs([prompts] * num_samples ) lowerCAmelCase__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ) lowerCAmelCase__ = pipe.prepare_image_inputs([canny_image] * num_samples ) lowerCAmelCase__ = jax.random.PRNGKey(0 ) lowerCAmelCase__ = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count() ) lowerCAmelCase__ = replicate(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = shard(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = shard(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = pipe( prompt_ids=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , prng_seed=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , jit=SCREAMING_SNAKE_CASE__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) lowerCAmelCase__ = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowerCAmelCase__ = images[0, 253:256, 253:256, -1] lowerCAmelCase__ = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowerCAmelCase__ = jnp.array( [0.167_969, 0.116_699, 0.081_543, 0.154_297, 0.132_812, 0.108_887, 0.169_922, 0.169_922, 0.205_078] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def a ( self : List[str] ) -> Any: lowerCAmelCase__ , lowerCAmelCase__ = FlaxControlNetModel.from_pretrained( "lllyasviel/sd-controlnet-openpose" , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa ) lowerCAmelCase__ , lowerCAmelCase__ = FlaxStableDiffusionControlNetPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , controlnet=SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa ) lowerCAmelCase__ = controlnet_params lowerCAmelCase__ = "Chef in the kitchen" lowerCAmelCase__ = jax.device_count() lowerCAmelCase__ = pipe.prepare_text_inputs([prompts] * num_samples ) lowerCAmelCase__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png" ) lowerCAmelCase__ = pipe.prepare_image_inputs([pose_image] * num_samples ) lowerCAmelCase__ = jax.random.PRNGKey(0 ) lowerCAmelCase__ = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count() ) lowerCAmelCase__ = replicate(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = shard(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = shard(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = pipe( prompt_ids=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , prng_seed=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , jit=SCREAMING_SNAKE_CASE__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) lowerCAmelCase__ = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowerCAmelCase__ = images[0, 253:256, 253:256, -1] lowerCAmelCase__ = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowerCAmelCase__ = jnp.array( [[0.271_484, 0.261_719, 0.275_391, 0.277_344, 0.279_297, 0.291_016, 0.294_922, 0.302_734, 0.302_734]] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
61
import math from datetime import datetime, timedelta def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Union[str, Any] = year % 1_9 __a : int = year % 4 __a : Optional[int] = year % 7 __a : Dict = math.floor(year / 1_0_0 ) __a : Optional[Any] = math.floor((1_3 + 8 * leap_day_inhibits) / 2_5 ) __a : Union[str, Any] = leap_day_inhibits / 4 __a : str = ( 1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 3_0 __a : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __a : List[Any] = (1_9 * metonic_cycle + secular_moon_shift) % 3_0 # PHM -> Paschal Full Moon __a : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 2_9 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_9 ) elif days_to_add == 2_8 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_8 ) else: return datetime(lowerCamelCase_ , 3 , 2_2 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): SCREAMING_SNAKE_CASE__ = '''will be''' if year > datetime.now().year else '''was''' print(F"Easter in {year} {tense} {gauss_easter(year)}")
47
0
def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [0] * len(lowercase ) SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : Dict = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowercase ) ): if indegree[i] == 0: queue.append(lowercase ) while queue: SCREAMING_SNAKE_CASE : Dict = queue.pop(0 ) cnt += 1 topo.append(lowercase ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(lowercase ) if cnt != len(lowercase ): print("Cycle exists" ) else: print(lowercase ) # Adjacency List of Graph snake_case = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
62
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = '''informer''' __SCREAMING_SNAKE_CASE : List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "student_t" , SCREAMING_SNAKE_CASE__ : str = "nll" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : List[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : int = 6_4 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.05 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str = "prob" , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Dict = prediction_length __a : Tuple = context_length or prediction_length __a : Tuple = distribution_output __a : Tuple = loss __a : str = input_size __a : Dict = num_time_features __a : Optional[int] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __a : str = scaling __a : Tuple = num_dynamic_real_features __a : int = num_static_real_features __a : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __a : Optional[Any] = cardinality else: __a : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __a : int = embedding_dimension else: __a : List[Any] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] __a : int = num_parallel_samples # Transformer architecture configuration __a : str = input_size * len(self.lags_sequence ) + self._number_of_features __a : Optional[int] = d_model __a : Union[str, Any] = encoder_attention_heads __a : int = decoder_attention_heads __a : Any = encoder_ffn_dim __a : Union[str, Any] = decoder_ffn_dim __a : List[Any] = encoder_layers __a : Optional[int] = decoder_layers __a : int = dropout __a : Optional[Any] = attention_dropout __a : Dict = activation_dropout __a : Union[str, Any] = encoder_layerdrop __a : Optional[int] = decoder_layerdrop __a : List[str] = activation_function __a : str = init_std __a : Optional[int] = use_cache # Informer __a : Union[str, Any] = attention_type __a : str = sampling_factor __a : Dict = distil super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
0
a : int = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" a : Optional[Any] = [{"type": "code", "content": INSTALL_CONTENT}] a : Optional[int] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
63
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE : Union[str, Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : List[str] = 1_0, 0.0 __a : Dict = self.dummy_model() __a : str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __a : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config(steps_offset=1 ) __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 1_0, 5_0] , [1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for t, eta in zip([1, 1_0, 4_9] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 , 4_0_0 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 , 9_6_0 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 , 4_8_6 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 , 9_9_8 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config() __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : Any = 1_0, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = self.dummy_model() __a : int = self.dummy_sample_deter __a : List[Any] = self.dummy_sample_deter + 0.1 __a : List[str] = self.dummy_sample_deter - 0.1 __a : Optional[Any] = samplea.shape[0] __a : Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) __a : Union[str, Any] = torch.arange(SCREAMING_SNAKE_CASE__ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE__ ) __a : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a : int = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE__ ) __a : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : List[str] = self.full_loop() __a : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : Dict = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
47
0
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin lowercase_ : Dict = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right lowercase_ : List[Any] = 2_5_6_0_4_7 lowercase_ : str = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class _lowerCamelCase ( UpperCamelCase_ , unittest.TestCase ): __a = NllbTokenizer __a = NllbTokenizerFast __a = True __a = True __a = {} def UpperCamelCase_ ( self ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__: str= NllbTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: Tuple= NllbTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: str= tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__: Optional[Any]= tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE__: Optional[int]= tokenizer.convert_tokens_to_ids(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) SCREAMING_SNAKE_CASE__: str= tokenizer.convert_ids_to_tokens(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def UpperCamelCase_ ( self ) -> List[Any]: SCREAMING_SNAKE_CASE__: Any= (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-nllb''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): SCREAMING_SNAKE_CASE__: int= self.rust_tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= self.tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[Any]= tempfile.mkdtemp() SCREAMING_SNAKE_CASE__: Tuple= tokenizer_r.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE__: Optional[int]= tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(lowerCAmelCase , lowerCAmelCase ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__: List[Any]= tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Dict= tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) shutil.rmtree(lowerCAmelCase ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE__: Dict= tempfile.mkdtemp() SCREAMING_SNAKE_CASE__: Union[str, Any]= tokenizer_r.save_pretrained(lowerCAmelCase , legacy_format=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Tuple= tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(lowerCAmelCase , lowerCAmelCase ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__: Optional[Any]= tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: str= tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) shutil.rmtree(lowerCAmelCase ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE__: Tuple= tempfile.mkdtemp() SCREAMING_SNAKE_CASE__: Optional[int]= tokenizer_r.save_pretrained(lowerCAmelCase , legacy_format=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[Any]= tokenizer_p.save_pretrained(lowerCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__: Union[str, Any]= tokenizer_r.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[Any]= tokenizer_p.from_pretrained(lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase , lowerCAmelCase ) ) shutil.rmtree(lowerCAmelCase ) @require_torch def UpperCamelCase_ ( self ) -> List[Any]: if not self.test_seqaseq: return SCREAMING_SNAKE_CASE__: Optional[int]= self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. SCREAMING_SNAKE_CASE__: Dict= [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for''' ''' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons''' ''' will only worsen the violence and misery for millions of people.''', ] SCREAMING_SNAKE_CASE__: Optional[Any]= [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al''' ''' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi''' ''' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] try: SCREAMING_SNAKE_CASE__: Any= tokenizer.prepare_seqaseq_batch( src_texts=lowerCAmelCase , tgt_texts=lowerCAmelCase , max_length=3 , max_target_length=10 , return_tensors='''pt''' , src_lang='''eng_Latn''' , tgt_lang='''ron_Latn''' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified SCREAMING_SNAKE_CASE__: str= tokenizer.prepare_seqaseq_batch( lowerCAmelCase , tgt_texts=lowerCAmelCase , max_length=3 , return_tensors='''pt''' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) SCREAMING_SNAKE_CASE__: Optional[int]= tokenizer.prepare_seqaseq_batch( src_texts=lowerCAmelCase , max_length=3 , max_target_length=10 , return_tensors='''pt''' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('''decoder_input_ids''' , lowerCAmelCase ) @unittest.skip('''Unfortunately way too slow to build a BPE with SentencePiece.''' ) def UpperCamelCase_ ( self ) -> Optional[int]: pass def UpperCamelCase_ ( self ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): SCREAMING_SNAKE_CASE__: Optional[int]= [AddedToken('''<special>''' , lstrip=lowerCAmelCase )] SCREAMING_SNAKE_CASE__: Dict= self.rust_tokenizer_class.from_pretrained( lowerCAmelCase , additional_special_tokens=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE__: int= tokenizer_r.encode('''Hey this is a <special> token''' ) SCREAMING_SNAKE_CASE__: Dict= tokenizer_r.encode('''<special>''' , add_special_tokens=lowerCAmelCase )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: SCREAMING_SNAKE_CASE__: int= self.rust_tokenizer_class.from_pretrained( lowerCAmelCase , additional_special_tokens=lowerCAmelCase , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE__: Dict= self.tokenizer_class.from_pretrained( lowerCAmelCase , additional_special_tokens=lowerCAmelCase , **lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= tokenizer_p.encode('''Hey this is a <special> token''' ) SCREAMING_SNAKE_CASE__: Optional[int]= tokenizer_cr.encode('''Hey this is a <special> token''' ) self.assertEqual(lowerCAmelCase , lowerCAmelCase ) self.assertEqual(lowerCAmelCase , lowerCAmelCase ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class _lowerCamelCase ( unittest.TestCase ): __a = "facebook/nllb-200-distilled-600M" __a = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] __a = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] __a = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCamelCase_ ( cls ) -> Optional[int]: SCREAMING_SNAKE_CASE__: NllbTokenizer= NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''eng_Latn''' , tgt_lang='''ron_Latn''' ) SCREAMING_SNAKE_CASE__: Any= 1 return cls def UpperCamelCase_ ( self ) -> int: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Arab'''] , 256001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ace_Latn'''] , 256002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''fra_Latn'''] , 256057 ) def UpperCamelCase_ ( self ) -> Any: SCREAMING_SNAKE_CASE__: Dict= self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase ) def UpperCamelCase_ ( self ) -> str: self.assertIn(lowerCAmelCase , self.tokenizer.all_special_ids ) # fmt: off SCREAMING_SNAKE_CASE__: Optional[Any]= [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: on SCREAMING_SNAKE_CASE__: Union[str, Any]= self.tokenizer.decode(lowerCAmelCase , skip_special_tokens=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase ) self.assertEqual(lowerCAmelCase , lowerCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase ) def UpperCamelCase_ ( self ) -> Dict: SCREAMING_SNAKE_CASE__: Union[str, Any]= ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Any= 10 SCREAMING_SNAKE_CASE__: List[Any]= self.tokenizer(lowerCAmelCase , max_length=lowerCAmelCase , truncation=lowerCAmelCase ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , lowerCAmelCase ) self.assertEqual(len(lowerCAmelCase ) , lowerCAmelCase ) def UpperCamelCase_ ( self ) -> Any: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [256203, 3] ) def UpperCamelCase_ ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE__: List[str]= tempfile.mkdtemp() SCREAMING_SNAKE_CASE__: Optional[int]= self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[Any]= NllbTokenizer.from_pretrained(lowerCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowerCAmelCase ) @require_torch def UpperCamelCase_ ( self ) -> str: SCREAMING_SNAKE_CASE__: Optional[Any]= self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase , truncation=lowerCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE__: List[Any]= shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['''ron_Latn'''] ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE__: Union[str, Any]= batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase ) self.assertEqual(lowerCAmelCase , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: List[str]= self.tokenizer(self.src_text , padding=lowerCAmelCase , truncation=lowerCAmelCase , max_length=3 , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__: Tuple= self.tokenizer( text_target=self.tgt_text , padding=lowerCAmelCase , truncation=lowerCAmelCase , max_length=10 , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE__: Optional[Any]= targets['''input_ids'''] SCREAMING_SNAKE_CASE__: Tuple= shift_tokens_right( lowerCAmelCase , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase_ ( self ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__: List[Any]= self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( nested_simplify(lowerCAmelCase ) , { # A, test, EOS, en_XX '''input_ids''': [[256047, 70, 7356, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 256057, } , ) @require_torch def UpperCamelCase_ ( self ) -> Any: SCREAMING_SNAKE_CASE__: Tuple= True SCREAMING_SNAKE_CASE__: List[Any]= self.tokenizer( '''UN Chief says there is no military solution in Syria''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( inputs.input_ids , [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047] ) SCREAMING_SNAKE_CASE__: Tuple= False SCREAMING_SNAKE_CASE__: str= self.tokenizer( '''UN Chief says there is no military solution in Syria''' , src_lang='''eng_Latn''' , tgt_lang='''fra_Latn''' ) self.assertEqual( inputs.input_ids , [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2] )
64
def UpperCAmelCase__ ( lowerCamelCase_ : list[int] , lowerCamelCase_ : list[int] ): # Check if the input is valid if not len(lowerCamelCase_ ) == len(lowerCamelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __a , __a , __a : Optional[Any] = equationa __a , __a , __a : Optional[int] = equationa # Calculate the determinants of the matrices __a : str = aa * ba - aa * ba __a : Tuple = ca * ba - ca * ba __a : Union[str, Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __a : Any = determinant_x / determinant __a : Optional[Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
47
0
"""simple docstring""" # using dfs for finding eulerian path traversal def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ): '''simple docstring''' UpperCAmelCase__ : List[Any] = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCAmelCase__ , UpperCAmelCase__ : List[str] = True, True UpperCAmelCase__ : Any = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) return path def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Union[str, Any] = -1 for i in range(__UpperCamelCase ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCAmelCase__ : str = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCAmelCase__ , UpperCAmelCase__ : int = check_circuit_or_path(__UpperCamelCase , __UpperCamelCase ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return UpperCAmelCase__ : Dict = 1 if check == 2: UpperCAmelCase__ : List[str] = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) UpperCAmelCase__ : str = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) print(__UpperCamelCase ) def lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ : str = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCAmelCase__ : List[str] = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCAmelCase__ : Union[str, Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCAmelCase__ : Optional[Any] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCAmelCase__ : List[str] = { 1: [], 2: [] # all degree is zero } UpperCAmelCase__ : Dict = 10 check_euler(__UpperCamelCase , __UpperCamelCase ) check_euler(__UpperCamelCase , __UpperCamelCase ) check_euler(__UpperCamelCase , __UpperCamelCase ) check_euler(__UpperCamelCase , __UpperCamelCase ) check_euler(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
65
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
47
0
def __magic_name__ ( SCREAMING_SNAKE_CASE = 50 ) -> int: _lowercase : Optional[int] = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
66
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
47
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """SCUT-DLVCLab/lilt-roberta-en-base""": ( """https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json""" ), } class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = '''lilt''' def __init__( self : int ,__A : List[Any]=3_0522 ,__A : Tuple=768 ,__A : Tuple=12 ,__A : Union[str, Any]=12 ,__A : Optional[int]=3072 ,__A : Union[str, Any]="gelu" ,__A : str=0.1 ,__A : List[str]=0.1 ,__A : Optional[Any]=512 ,__A : List[str]=2 ,__A : Optional[int]=0.02 ,__A : Dict=1e-12 ,__A : str=0 ,__A : Tuple="absolute" ,__A : Union[str, Any]=None ,__A : Dict=4 ,__A : List[str]=1024 ,**__A : int ,) -> Any: super().__init__(pad_token_id=__A ,**__A ) _lowercase = vocab_size _lowercase = hidden_size _lowercase = num_hidden_layers _lowercase = num_attention_heads _lowercase = hidden_act _lowercase = intermediate_size _lowercase = hidden_dropout_prob _lowercase = attention_probs_dropout_prob _lowercase = max_position_embeddings _lowercase = type_vocab_size _lowercase = initializer_range _lowercase = layer_norm_eps _lowercase = position_embedding_type _lowercase = classifier_dropout _lowercase = channel_shrink_ratio _lowercase = max_ad_position_embeddings
67
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
0
import os def lowercase__ ( ) -> Optional[Any]: """simple docstring""" with open(os.path.dirname(A_ ) + """/p022_names.txt""" ) as file: __UpperCAmelCase =str(file.readlines()[0] ) __UpperCAmelCase =names.replace("""\"""" , """""" ).split(""",""" ) names.sort() __UpperCAmelCase =0 __UpperCAmelCase =0 for i, name in enumerate(A_ ): for letter in name: name_score += ord(A_ ) - 64 total_score += (i + 1) * name_score __UpperCAmelCase =0 return total_score if __name__ == "__main__": print(solution())
68
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''sew-d''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=("p2c", "c2p") , SCREAMING_SNAKE_CASE__ : str="layer_norm" , SCREAMING_SNAKE_CASE__ : Tuple="gelu_python" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-7 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Optional[int]="group" , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : str=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2_8 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]="mean" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=2_5_6 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = hidden_size __a : Optional[Any] = feat_extract_norm __a : List[str] = feat_extract_activation __a : Dict = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = list(SCREAMING_SNAKE_CASE__ ) __a : List[str] = list(SCREAMING_SNAKE_CASE__ ) __a : int = conv_bias __a : Tuple = num_conv_pos_embeddings __a : List[str] = num_conv_pos_embedding_groups __a : Optional[Any] = len(self.conv_dim ) __a : Union[str, Any] = num_hidden_layers __a : Optional[Any] = intermediate_size __a : Union[str, Any] = squeeze_factor __a : List[Any] = max_position_embeddings __a : Tuple = position_buckets __a : Optional[int] = share_att_key __a : List[str] = relative_attention __a : Any = norm_rel_ebd __a : Any = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = hidden_act __a : str = num_attention_heads __a : Union[str, Any] = hidden_dropout __a : Optional[int] = attention_dropout __a : List[str] = activation_dropout __a : int = feat_proj_dropout __a : int = final_dropout __a : Dict = layer_norm_eps __a : Tuple = feature_layer_norm_eps __a : str = initializer_range __a : Tuple = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : Tuple = apply_spec_augment __a : Optional[Any] = mask_time_prob __a : Any = mask_time_length __a : List[str] = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Tuple = mask_feature_length __a : Any = mask_feature_min_masks # ctc loss __a : Optional[int] = ctc_loss_reduction __a : List[Any] = ctc_zero_infinity # sequence classification __a : Dict = use_weighted_layer_sum __a : Optional[Any] = classifier_proj_size @property def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
47
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a : Optional[Any] = logging.get_logger(__name__) a : Dict = {'''vocab_file''': '''sentencepiece.model'''} a : Tuple = { '''vocab_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''', }, } a : str = { '''google/rembert''': 256, } class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ): """simple docstring""" super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , ) __snake_case = do_lower_case __snake_case = remove_space __snake_case = keep_accents __snake_case = vocab_file __snake_case = spm.SentencePieceProcessor() self.sp_model.Load(a_ ) @property def A ( self : Optional[Any] ): """simple docstring""" return len(self.sp_model ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ): """simple docstring""" __snake_case = self.__dict__.copy() __snake_case = None return state def __setstate__( self : str , a_ : Optional[int] ): """simple docstring""" __snake_case = d __snake_case = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ): """simple docstring""" __snake_case = self.sp_model.EncodeAsPieces(a_ ) return pieces def A ( self : Any , a_ : Optional[Any] ): """simple docstring""" return self.sp_model.PieceToId(a_ ) def A ( self : Optional[Any] , a_ : List[str] ): """simple docstring""" return self.sp_model.IdToPiece(a_ ) def A ( self : Optional[Any] , a_ : int ): """simple docstring""" __snake_case = self.sp_model.decode_pieces(a_ ) return out_string def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ): """simple docstring""" __snake_case = [self.sep_token_id] __snake_case = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ): """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1] return [1] + ([0] * len(a_ )) + [1] def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ): """simple docstring""" __snake_case = [self.sep_token_id] __snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(a_ ): logger.error("Vocabulary path ({}) should be a directory".format(a_ ) ) return __snake_case = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) return (out_vocab_file,)
69
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
0
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _SCREAMING_SNAKE_CASE ( lowercase : List[str] , lowercase : List[Any]=() , lowercase : Any=None , lowercase : str="no" , lowercase : int="29500" ): '''simple docstring''' lowerCamelCase_ = False lowerCamelCase_ = False if any(key.startswith('KAGGLE' ) for key in os.environ.keys() ): lowerCamelCase_ = True elif "IPython" in sys.modules: lowerCamelCase_ = 'google.colab' in str(sys.modules['IPython'].get_ipython() ) try: lowerCamelCase_ = 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' , lowercase ) 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: lowerCamelCase_ = 8 lowerCamelCase_ = PrepareForLaunch(lowercase , distributed_type='TPU' ) print(f"""Launching a training on {num_processes} TPU cores.""" ) xmp.spawn(lowercase , args=lowercase , nprocs=lowercase , 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(*lowercase ) 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=lowercase , master_addr='127.0.01' , master_port=lowercase , mixed_precision=lowercase ): lowerCamelCase_ = PrepareForLaunch(lowercase , distributed_type='MULTI_GPU' ) print(f"""Launching training on {num_processes} GPUs.""" ) try: start_processes(lowercase , args=lowercase , nprocs=lowercase , 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(): lowerCamelCase_ = '1' print('Launching training on MPS.' ) elif torch.cuda.is_available(): print('Launching training on one GPU.' ) else: print('Launching training on CPU.' ) function(*lowercase ) def _SCREAMING_SNAKE_CASE ( lowercase : List[str] , lowercase : Tuple=() , lowercase : Any=2 ): '''simple docstring''' 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=lowercase , master_addr='127.0.01' , master_port='29500' , accelerate_mixed_precision='no' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='yes' , ): lowerCamelCase_ = PrepareForLaunch(lowercase , debug=lowercase ) start_processes(lowercase , args=lowercase , nprocs=lowercase , start_method='fork' )
70
from collections.abc import Sequence from queue import Queue class _UpperCamelCase: def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None ): '''simple docstring''' __a : Tuple = start __a : Dict = end __a : List[str] = val __a : List[Any] = (start + end) // 2 __a : Optional[Any] = left __a : List[str] = right def __repr__( self : Dict ): '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class _UpperCamelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Sequence , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Tuple = collection __a : Dict = function if self.collection: __a : int = self._build_tree(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.collection[start] ) __a : Tuple = (start + end) // 2 __a : Optional[int] = self._build_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Tuple = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE__ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if node.start == i and node.end == i: __a : Optional[Any] = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = self.fn(node.left.val , node.right.val ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE__ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE__ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' if self.root is not None: __a : Tuple = Queue() queue.put(self.root ) while not queue.empty(): __a : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) SCREAMING_SNAKE_CASE__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
47
0
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { """configuration_gpt_neox_japanese""": ["""GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXJapaneseConfig"""], """tokenization_gpt_neox_japanese""": ["""GPTNeoXJapaneseTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ """GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXJapaneseForCausalLM""", """GPTNeoXJapaneseLayer""", """GPTNeoXJapaneseModel""", """GPTNeoXJapanesePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
71
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int SCREAMING_SNAKE_CASE__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _UpperCamelCase( datasets.BuilderConfig ): __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None def UpperCAmelCase__ ( lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[int] , ): import pyspark def generate_fn(): __a : List[Any] = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __a : Optional[int] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __a : Optional[Any] = partition_df.collect() __a : Union[str, Any] = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _UpperCamelCase( _BaseExamplesIterable ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : Dict=None , ): '''simple docstring''' __a : List[str] = df __a : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) __a : List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.random.Generator ): '''simple docstring''' __a : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return len(self.partition_order ) class _UpperCamelCase( datasets.DatasetBuilder ): __SCREAMING_SNAKE_CASE : List[str] = SparkConfig def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' import pyspark __a : int = pyspark.sql.SparkSession.builder.getOrCreate() __a : Optional[int] = df __a : List[Any] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__ : List[str] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE__ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __a : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE__ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE__ : int ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __a : List[str] = self.df.count() __a : Dict = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __a : List[str] = ( self.df.limit(SCREAMING_SNAKE_CASE__ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE__ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __a : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __a : Union[str, Any] = min(SCREAMING_SNAKE_CASE__ , int(approx_total_size / max_shard_size ) ) __a : int = self.df.repartition(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , ): '''simple docstring''' import pyspark __a : Any = ParquetWriter if file_format == 'parquet' else ArrowWriter __a : Union[str, Any] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) if self._working_dir else fpath __a : Optional[int] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __a : List[str] = self.config.features __a : int = self._writer_batch_size __a : Union[str, Any] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __a : Any = pyspark.TaskContext().taskAttemptId() __a : str = next(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __a : Any = 0 __a : List[str] = writer_class( features=SCREAMING_SNAKE_CASE__ , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __a , __a : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __a : Optional[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Union[str, Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) if writer._num_bytes > 0: __a , __a : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ): __a : Any = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ) , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) shutil.move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE__ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , SCREAMING_SNAKE_CASE__ : str = "arrow" , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' self._validate_cache_dir() __a : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = not is_remote_filesystem(self._fs ) __a : Optional[Any] = os.path.join if is_local else posixpath.join __a : Any = '-TTTTT-SSSSS-of-NNNNN' __a : Union[str, Any] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __a : Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE__ ) __a : Any = 0 __a : Dict = 0 __a : int = 0 __a : List[str] = [] __a : Optional[int] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE__ ) __a : List[str] = total_num_examples __a : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __a : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __a : Dict = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): rename( SCREAMING_SNAKE_CASE__ , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __a : Union[str, Any] = [] __a : List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a , __a : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE__ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ).map(lambda SCREAMING_SNAKE_CASE__ : _rename_shard(*SCREAMING_SNAKE_CASE__ ) ).collect() else: # don't use any pattern __a : List[Any] = 0 __a : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE__ , '' ) , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
47
0
'''simple docstring''' from math import ceil, sqrt def UpperCamelCase ( lowercase_ : int = 1_0_0_0_0_0_0 ) -> int: '''simple docstring''' lowercase =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowercase =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowercase =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F"""{solution() = }""")
72
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : int ): # save results if os.path.exists(lowerCamelCase_ ): if os.path.exists(os.path.join(lowerCamelCase_ , 'config.json' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'config.json' ) ): os.remove(os.path.join(lowerCamelCase_ , 'config.json' ) ) if os.path.exists(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ): os.remove(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) else: os.makedirs(lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : Any=False ): __a : Dict = 2 if unlogit: __a : Optional[Any] = torch.pow(lowerCamelCase_ , lowerCamelCase_ ) __a : Any = p * torch.log(lowerCamelCase_ ) __a : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ ( lowerCamelCase_ : Any ): logger.info('lv, h >\t' + '\t'.join(f'''{x + 1}''' for x in range(len(lowerCamelCase_ ) ) ) ) for row in range(len(lowerCamelCase_ ) ): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:d}''' for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=False ): __a , __a : Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads __a : str = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) __a : int = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) if head_mask is None: __a : Union[str, Any] = torch.ones(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCamelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __a : Any = None __a : Optional[int] = 0.0 __a : Optional[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCamelCase_ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __a : Dict = tuple(t.to(args.device ) for t in inputs ) ((__a) , ) : Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __a : List[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ , head_mask=lowerCamelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __a , __a , __a : int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCamelCase_ ): __a : List[str] = entropy(attn.detach() , lowerCamelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCamelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __a : Optional[Any] = 2 __a : Union[str, Any] = torch.pow(torch.pow(lowerCamelCase_ , lowerCamelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: __a : List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(lowerCamelCase_ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(lowerCamelCase_ ) logger.info('Head ranked by importance scores' ) __a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __a : str = torch.arange( head_importance.numel() , device=args.device ) __a : Tuple = head_ranks.view_as(lowerCamelCase_ ) print_ad_tensor(lowerCamelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): __a , __a , __a : Optional[int] = compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ ) __a : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , lowerCamelCase_ , original_score * args.masking_threshold ) __a : Tuple = torch.ones_like(lowerCamelCase_ ) __a : int = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __a : Tuple = original_score while current_score >= original_score * args.masking_threshold: __a : Optional[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __a : List[str] = float('Inf' ) __a : List[Any] = head_importance.view(-1 ).sort()[1] if len(lowerCamelCase_ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __a : Any = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __a : int = new_head_mask.view(-1 ) __a : Tuple = 0.0 __a : int = new_head_mask.view_as(lowerCamelCase_ ) __a : Optional[int] = new_head_mask.clone().detach() print_ad_tensor(lowerCamelCase_ ) # Compute metric and head importance again __a , __a , __a : int = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[Any] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowerCamelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(lowerCamelCase_ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): __a : List[Any] = datetime.now() __a , __a , __a : List[str] = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[str] = 1 / loss __a : List[Any] = datetime.now() - before_time __a : List[str] = sum(p.numel() for p in model.parameters() ) __a : Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __a : Tuple = [ v, ] assert sum(len(lowerCamelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCamelCase_ ) __a : Optional[Any] = sum(p.numel() for p in model.parameters() ) __a : Tuple = datetime.now() __a , __a , __a : Tuple = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ , actually_pruned=lowerCamelCase_ , ) __a : Optional[Any] = 1 / loss __a : List[Any] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowerCamelCase_ , lowerCamelCase_ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , lowerCamelCase_ , lowerCamelCase_ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(lowerCamelCase_ , args.output_dir ) def UpperCAmelCase__ ( ): __a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=lowerCamelCase_ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=lowerCamelCase_ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=lowerCamelCase_ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=lowerCamelCase_ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=lowerCamelCase_ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=lowerCamelCase_ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=lowerCamelCase_ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=lowerCamelCase_ , help='Batch size.' ) parser.add_argument('--seed' , type=lowerCamelCase_ , default=4_2 ) parser.add_argument('--local_rank' , type=lowerCamelCase_ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) __a : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCamelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __a : List[str] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __a : Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __a : Union[str, Any] = torch.device('cuda' , args.local_rank ) __a : Any = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __a : Optional[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __a : List[Any] = nn.parallel.DistributedDataParallel( lowerCamelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCamelCase_ ) elif args.n_gpu > 1: __a : Union[str, Any] = nn.DataParallel(lowerCamelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , lowerCamelCase_ ) # Prepare dataset __a : Tuple = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __a : str = (torch.from_numpy(lowerCamelCase_ ),) __a : List[str] = TensorDataset(*lowerCamelCase_ ) __a : Optional[Any] = RandomSampler(lowerCamelCase_ ) __a : Union[str, Any] = DataLoader(lowerCamelCase_ , sampler=lowerCamelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __a : Union[str, Any] = mask_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) prune_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
47
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( A__ ): _lowercase : Tuple = ['''image_processor''', '''tokenizer'''] _lowercase : List[Any] = '''ViTImageProcessor''' _lowercase : Optional[Any] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self , a=None , a=None , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) SCREAMING_SNAKE_CASE = kwargs.pop('feature_extractor') SCREAMING_SNAKE_CASE = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(a , a) def __call__( self , a=None , a=None , a=None , a=None , **a) -> int: if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.') if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.') if text is not None: SCREAMING_SNAKE_CASE = self.tokenizer(a , return_tensors=a , **a) if visual_prompt is not None: SCREAMING_SNAKE_CASE = self.image_processor(a , return_tensors=a , **a) if images is not None: SCREAMING_SNAKE_CASE = self.image_processor(a , return_tensors=a , **a) if visual_prompt is not None and images is not None: SCREAMING_SNAKE_CASE = { 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: SCREAMING_SNAKE_CASE = { 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**a) , tensor_type=a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]: return self.tokenizer.batch_decode(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> int: return self.tokenizer.decode(*a , **a) @property def SCREAMING_SNAKE_CASE__ ( self) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a , ) return self.image_processor
73
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __a : List[Any] = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1_0_2_4, 'hidden_size': 7_6_8, 'max_length': 5_1_2, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1_0_2_4, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __a : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a : List[str] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a : int = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __a : Optional[Any] = os.path.join(get_home_dir() , 'models' ) __a : Optional[Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __a : Any = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __a : Dict = original_bort._collect_params_with_prefix() # Build our config 🤗 __a : Optional[Any] = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(lowerCamelCase_ ), } __a : str = BertConfig.from_dict(lowerCamelCase_ ) __a : Optional[int] = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Optional[Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __a : Optional[int] = hf_param.shape __a : int = to_torch(params[gluon_param] ) __a : int = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __a : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __a : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __a : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __a : BertSelfAttention = layer.attention.self __a : Optional[int] = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a : str = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a : str = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a : Dict = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a : str = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a : BertSelfOutput = layer.attention.output __a : Tuple = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a : Dict = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a : BertIntermediate = layer.intermediate __a : List[str] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a : Optional[Any] = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a : BertOutput = layer.output __a : str = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a : List[Any] = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a : List[str] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a : Union[str, Any] = RobertaTokenizer.from_pretrained('roberta-base' ) __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ )['input_ids'] # Get gluon output __a : Optional[int] = mx.nd.array([input_ids] ) __a : Tuple = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __a : Optional[Any] = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ , return_tensors='pt' ) __a : int = hf_bort_model(**lowerCamelCase_ )[0] __a : Dict = output_gluon[0].asnumpy() __a : str = output_hf[0].detach().numpy() __a : List[Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a : str = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
47
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""", } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = '''open-llama''' def __init__( self : List[str] , _A : int=10_0000 , _A : Dict=4096 , _A : int=1_1008 , _A : str=32 , _A : str=32 , _A : Dict="silu" , _A : List[str]=2048 , _A : Optional[Any]=0.02 , _A : Union[str, Any]=1e-6 , _A : Optional[Any]=True , _A : Tuple=0 , _A : List[Any]=1 , _A : str=2 , _A : str=False , _A : Any=True , _A : List[Any]=0.1 , _A : Optional[int]=0.1 , _A : Any=True , _A : Any=True , _A : Optional[int]=None , **_A : Optional[int] , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings __SCREAMING_SNAKE_CASE : Dict = hidden_size __SCREAMING_SNAKE_CASE : Tuple = intermediate_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads __SCREAMING_SNAKE_CASE : str = hidden_act __SCREAMING_SNAKE_CASE : Any = initializer_range __SCREAMING_SNAKE_CASE : Dict = rms_norm_eps __SCREAMING_SNAKE_CASE : int = use_cache __SCREAMING_SNAKE_CASE : List[str] = kwargs.pop( '''use_memorry_efficient_attention''' , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : str = attention_dropout_prob __SCREAMING_SNAKE_CASE : List[str] = use_stable_embedding __SCREAMING_SNAKE_CASE : Dict = shared_input_output_embedding __SCREAMING_SNAKE_CASE : int = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A , ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F'''got {self.rope_scaling}''' ) __SCREAMING_SNAKE_CASE : List[str] = self.rope_scaling.get('''type''' , _A ) __SCREAMING_SNAKE_CASE : Any = self.rope_scaling.get('''factor''' , _A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
74
def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ): __a : Any = '' for i in table: res += inp[i - 1] return res def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] ): return data[1:] + data[0] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): __a : Optional[int] = '' for i in range(len(lowerCamelCase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): __a : List[str] = int('0b' + data[0] + data[-1] , 2 ) __a : List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = message[:4] __a : str = message[4:] __a : Any = apply_table(lowerCamelCase_ , lowerCamelCase_ ) __a : int = xor(lowerCamelCase_ , lowerCamelCase_ ) __a : Dict = apply_sbox(lowerCamelCase_ , temp[:4] ) # noqa: E741 __a : Tuple = apply_sbox(lowerCamelCase_ , temp[4:] ) __a : List[Any] = '0' * (2 - len(lowerCamelCase_ )) + l # noqa: E741 __a : List[str] = '0' * (2 - len(lowerCamelCase_ )) + r __a : List[Any] = apply_table(l + r , lowerCamelCase_ ) __a : Dict = xor(lowerCamelCase_ , lowerCamelCase_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE__ = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE__ = [6, 3, 7, 4, 8, 5, 10, 9] SCREAMING_SNAKE_CASE__ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] SCREAMING_SNAKE_CASE__ = [2, 4, 3, 1] SCREAMING_SNAKE_CASE__ = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE__ = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE__ = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE__ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE__ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE__ = apply_table(key, paa_table) SCREAMING_SNAKE_CASE__ = temp[:5] SCREAMING_SNAKE_CASE__ = temp[5:] SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE__ = apply_table(message, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE__ = apply_table(CT, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
47
0
'''simple docstring''' import json import sys def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: UpperCAmelCase__ : Union[str, Any] = json.load(lowerCAmelCase__ ) UpperCAmelCase__ : str = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' '''] for benchmark_name in sorted(lowerCAmelCase__ ): UpperCAmelCase__ : int = results[benchmark_name] UpperCAmelCase__ : Optional[int] = benchmark_name.split('''/''' )[-1] output_md.append(F"""### Benchmark: {benchmark_file_name}""" ) UpperCAmelCase__ : Optional[Any] = '''| metric |''' UpperCAmelCase__ : str = '''|--------|''' UpperCAmelCase__ : List[Any] = '''| new / old (diff) |''' for metric_name in sorted(lowerCAmelCase__ ): UpperCAmelCase__ : Union[str, Any] = benchmark_res[metric_name] UpperCAmelCase__ : List[Any] = metric_vals['''new'''] UpperCAmelCase__ : int = metric_vals.get('''old''' , lowerCAmelCase__ ) UpperCAmelCase__ : Union[str, Any] = metric_vals.get('''diff''' , lowerCAmelCase__ ) UpperCAmelCase__ : Any = F""" {new_val:f}""" if isinstance(lowerCAmelCase__ , (int, float) ) else '''None''' if old_val is not None: val_str += F""" / {old_val:f}""" if isinstance(lowerCAmelCase__ , (int, float) ) else "None" if dif_val is not None: val_str += F""" ({dif_val:f})""" if isinstance(lowerCAmelCase__ , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append('''</details>''' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.writelines('''\n'''.join(lowerCAmelCase__ ) ) if __name__ == "__main__": UpperCamelCase__ = sys.argv[1] UpperCamelCase__ = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
75
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class UpperCAmelCase_ ( snake_case ): UpperCamelCase ="swinv2" UpperCamelCase ={ "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , UpperCamelCase_=2_24 , UpperCamelCase_=4 , UpperCamelCase_=3 , UpperCamelCase_=96 , UpperCamelCase_=[2, 2, 6, 2] , UpperCamelCase_=[3, 6, 12, 24] , UpperCamelCase_=7 , UpperCamelCase_=4.0 , UpperCamelCase_=True , UpperCamelCase_=0.0 , UpperCamelCase_=0.0 , UpperCamelCase_=0.1 , UpperCamelCase_="gelu" , UpperCamelCase_=False , UpperCamelCase_=0.0_2 , UpperCamelCase_=1E-5 , UpperCamelCase_=32 , **UpperCamelCase_ , ) -> List[Any]: super().__init__(**UpperCamelCase_ ) __lowercase : Union[str, Any] = image_size __lowercase : Optional[int] = patch_size __lowercase : int = num_channels __lowercase : List[str] = embed_dim __lowercase : List[Any] = depths __lowercase : List[str] = len(UpperCamelCase_ ) __lowercase : List[Any] = num_heads __lowercase : Optional[int] = window_size __lowercase : int = mlp_ratio __lowercase : Any = qkv_bias __lowercase : Optional[int] = hidden_dropout_prob __lowercase : Tuple = attention_probs_dropout_prob __lowercase : Optional[int] = drop_path_rate __lowercase : Tuple = hidden_act __lowercase : Tuple = use_absolute_embeddings __lowercase : Dict = layer_norm_eps __lowercase : Dict = initializer_range __lowercase : Optional[Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __lowercase : Optional[int] = int(embed_dim * 2 ** (len(UpperCamelCase_ ) - 1) ) __lowercase : Union[str, Any] = (0, 0, 0, 0)
76
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''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 _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''roberta''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : str=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = vocab_size __a : Tuple = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : str = hidden_act __a : Optional[Any] = intermediate_size __a : Dict = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Dict = type_vocab_size __a : str = initializer_range __a : List[str] = layer_norm_eps __a : Optional[int] = position_embedding_type __a : Union[str, Any] = use_cache __a : str = classifier_dropout class _UpperCamelCase( __lowerCamelCase ): @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' if self.task == "multiple-choice": __a : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
0
"""simple docstring""" import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors A = logging.getLogger(__name__) class a__ ( __magic_name__ ): lowercase_ = "sequence-classification" def __init__( self : Optional[Any] , UpperCamelCase_ : int): """simple docstring""" if type(UpperCamelCase_) == dict: __UpperCAmelCase : Optional[int] = Namespace(**UpperCamelCase_) __UpperCAmelCase : Union[str, Any] = glue_output_modes[hparams.task] __UpperCAmelCase : Optional[Any] = glue_tasks_num_labels[hparams.task] super().__init__(UpperCamelCase_ , UpperCamelCase_ , self.mode) def a_ ( self : Optional[Any] , **UpperCamelCase_ : Optional[int]): """simple docstring""" return self.model(**UpperCamelCase_) def a_ ( self : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : int): """simple docstring""" __UpperCAmelCase : Optional[int] = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase : str = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __UpperCAmelCase : Optional[Any] = self(**UpperCamelCase_) __UpperCAmelCase : int = outputs[0] __UpperCAmelCase : str = self.trainer.lr_schedulers[0]["scheduler"] __UpperCAmelCase : Optional[int] = {"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def a_ ( self : Any): """simple docstring""" __UpperCAmelCase : Any = self.hparams __UpperCAmelCase : List[Any] = processors[args.task]() __UpperCAmelCase : Dict = processor.get_labels() for mode in ["train", "dev"]: __UpperCAmelCase : str = self._feature_file(UpperCamelCase_) if os.path.exists(UpperCamelCase_) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , UpperCamelCase_) else: logger.info("Creating features from dataset file at %s" , args.data_dir) __UpperCAmelCase : Optional[int] = ( processor.get_dev_examples(args.data_dir) if mode == "dev" else processor.get_train_examples(args.data_dir) ) __UpperCAmelCase : List[Any] = convert_examples_to_features( UpperCamelCase_ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("Saving features into cached file %s" , UpperCamelCase_) torch.save(UpperCamelCase_ , UpperCamelCase_) def a_ ( self : Tuple , UpperCamelCase_ : str , UpperCamelCase_ : int , UpperCamelCase_ : bool = False): """simple docstring""" __UpperCAmelCase : Dict = "dev" if mode == "test" else mode __UpperCAmelCase : Dict = self._feature_file(UpperCamelCase_) logger.info("Loading features from cached file %s" , UpperCamelCase_) __UpperCAmelCase : Dict = torch.load(UpperCamelCase_) __UpperCAmelCase : List[str] = torch.tensor([f.input_ids for f in features] , dtype=torch.long) __UpperCAmelCase : int = torch.tensor([f.attention_mask for f in features] , dtype=torch.long) __UpperCAmelCase : Optional[Any] = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase : int = torch.tensor([f.label for f in features] , dtype=torch.long) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase : Optional[Any] = torch.tensor([f.label for f in features] , dtype=torch.float) return DataLoader( TensorDataset(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) , batch_size=UpperCamelCase_ , shuffle=UpperCamelCase_ , ) def a_ ( self : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[Any]): """simple docstring""" __UpperCAmelCase : List[str] = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCAmelCase : List[Any] = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __UpperCAmelCase : Any = self(**UpperCamelCase_) __UpperCAmelCase , __UpperCAmelCase : Tuple = outputs[:2] __UpperCAmelCase : List[Any] = logits.detach().cpu().numpy() __UpperCAmelCase : List[Any] = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def a_ ( self : List[Any] , UpperCamelCase_ : List[Any]): """simple docstring""" __UpperCAmelCase : Union[str, Any] = torch.stack([x["val_loss"] for x in outputs]).mean().detach().cpu().item() __UpperCAmelCase : int = np.concatenate([x["pred"] for x in outputs] , axis=0) if self.hparams.glue_output_mode == "classification": __UpperCAmelCase : str = np.argmax(UpperCamelCase_ , axis=1) elif self.hparams.glue_output_mode == "regression": __UpperCAmelCase : Union[str, Any] = np.squeeze(UpperCamelCase_) __UpperCAmelCase : List[str] = np.concatenate([x["target"] for x in outputs] , axis=0) __UpperCAmelCase : Optional[Any] = [[] for _ in range(out_label_ids.shape[0])] __UpperCAmelCase : Any = [[] for _ in range(out_label_ids.shape[0])] __UpperCAmelCase : Union[str, Any] = {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task , UpperCamelCase_ , UpperCamelCase_)} __UpperCAmelCase : Optional[int] = dict(results.items()) __UpperCAmelCase : str = results return ret, preds_list, out_label_list def a_ ( self : Union[str, Any] , UpperCamelCase_ : list): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Dict = self._eval_end(UpperCamelCase_) __UpperCAmelCase : List[Any] = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def a_ ( self : List[str] , UpperCamelCase_ : str): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Tuple = self._eval_end(UpperCamelCase_) __UpperCAmelCase : Any = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def a_ ( UpperCamelCase_ : Any , UpperCamelCase_ : List[Any]): """simple docstring""" BaseTransformer.add_model_specific_args(UpperCamelCase_ , UpperCamelCase_) parser.add_argument( "--max_seq_length" , default=128 , type=UpperCamelCase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--task" , default="" , type=UpperCamelCase_ , required=UpperCamelCase_ , help="The GLUE task to run" , ) parser.add_argument( "--gpus" , default=0 , type=UpperCamelCase_ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets") return parser def _UpperCamelCase ( ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase : str = argparse.ArgumentParser() add_generic_args(UpperCamelCase , os.getcwd() ) __UpperCAmelCase : int = GLUETransformer.add_model_specific_args(UpperCamelCase , os.getcwd() ) __UpperCAmelCase : List[str] = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCAmelCase : Union[str, Any] = os.path.join( "./results" , f"{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}" , ) os.makedirs(args.output_dir ) __UpperCAmelCase : Tuple = GLUETransformer(UpperCamelCase ) __UpperCAmelCase : int = generic_train(UpperCamelCase , UpperCamelCase ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCAmelCase : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir , "checkpoint-epoch=*.ckpt" ) , recursive=UpperCamelCase ) ) __UpperCAmelCase : Tuple = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(UpperCamelCase ) if __name__ == "__main__": main()
77
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''▁''' SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } SCREAMING_SNAKE_CASE__ = { '''facebook/xglm-564M''': 2048, } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="<unk>" , SCREAMING_SNAKE_CASE__ : Dict="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer __a : Any = 7 __a : Union[str, Any] = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words )] __a : Union[str, Any] = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) __a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Any = 1 # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __a : List[str] = len(self.sp_model ) __a : Optional[int] = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) __a : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[str] ): '''simple docstring''' __a : Tuple = self.__dict__.copy() __a : List[str] = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Dict = {} __a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a __a : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
'''simple docstring''' from torch import nn def lowerCAmelCase_ ( snake_case_ : int ) -> Dict: '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"""Unsupported activation function: {act_fn}""" )
78
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] SCREAMING_SNAKE_CASE__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] ): __a : str = torch.load(lowerCamelCase_ , map_location='cpu' ) return sd def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict=rename_keys_prefix ): __a : Optional[Any] = OrderedDict() __a : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a : List[Any] = key for name_pair in rename_keys_prefix: __a : List[str] = new_key.replace(name_pair[0] , name_pair[1] ) __a : Any = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a : int = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : Any ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a : Dict = 'pretraining' if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __a : int = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __a : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} __a : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __a : Any = {'visual_embedding_dim': 2_0_4_8} __a : List[str] = 'vqa_advanced' elif "vqa" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __a : List[Any] = 'vqa' elif "nlvr" in checkpoint_path: __a : Optional[int] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __a : Optional[Any] = 'nlvr' __a : str = VisualBertConfig(**lowerCamelCase_ ) # Load State Dict __a : str = load_state_dict(lowerCamelCase_ ) __a : str = get_new_dict(lowerCamelCase_ , lowerCamelCase_ ) if model_type == "pretraining": __a : Optional[Any] = VisualBertForPreTraining(lowerCamelCase_ ) elif model_type == "vqa": __a : Any = VisualBertForQuestionAnswering(lowerCamelCase_ ) elif model_type == "nlvr": __a : int = VisualBertForVisualReasoning(lowerCamelCase_ ) elif model_type == "multichoice": __a : Optional[int] = VisualBertForMultipleChoice(lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # Save Checkpoints Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
47
0
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase_ ( __lowerCamelCase ): def __UpperCAmelCase ( self , _lowerCAmelCase ): return 0.0 def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> tuple[int | float, int | float]: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) UpperCAmelCase__ : int = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> None: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = 512 UpperCAmelCase__ : int = [1] + [0] * (size - 1) UpperCAmelCase__ : str = [filter_type.process(__lowerCamelCase ) for item in inputs] UpperCAmelCase__ : List[str] = [0] * (samplerate - size) # zero-padding outputs += filler UpperCAmelCase__ : List[str] = np.abs(np.fft.fft(__lowerCamelCase ) ) UpperCAmelCase__ : Any = 20 * np.logaa(__lowerCamelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("""Frequency (Hz)""" ) plt.xscale("""log""" ) # Display within reasonable bounds UpperCAmelCase__ : int = get_bounds(__lowerCamelCase , __lowerCamelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("""Gain (dB)""" ) plt.plot(__lowerCamelCase ) plt.show() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> None: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = 512 UpperCAmelCase__ : Any = [1] + [0] * (size - 1) UpperCAmelCase__ : int = [filter_type.process(__lowerCamelCase ) for item in inputs] UpperCAmelCase__ : Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler UpperCAmelCase__ : Optional[int] = np.angle(np.fft.fft(__lowerCamelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("""Frequency (Hz)""" ) plt.xscale("""log""" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("""Phase shift (Radians)""" ) plt.plot(np.unwrap(__lowerCamelCase , -2 * pi ) ) plt.show()
79
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
47
0
import math def snake_case ( lowerCamelCase ): '''simple docstring''' __lowercase = [] __lowercase = 2 __lowercase = int(math.sqrt(lowerCamelCase ) ) # Size of every segment __lowercase = [True] * (end + 1) __lowercase = [] while start <= end: if temp[start] is True: in_prime.append(lowerCamelCase ) for i in range(start * start , end + 1 , lowerCamelCase ): __lowercase = False start += 1 prime += in_prime __lowercase = end + 1 __lowercase = min(2 * end , lowerCamelCase ) while low <= n: __lowercase = [True] * (high - low + 1) for each in in_prime: __lowercase = math.floor(low / each ) * each if t < low: t += each for j in range(lowerCamelCase , high + 1 , lowerCamelCase ): __lowercase = False for j in range(len(lowerCamelCase ) ): if temp[j] is True: prime.append(j + low ) __lowercase = high + 1 __lowercase = min(high + end , lowerCamelCase ) return prime print(sieve(10**6))
80
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class _UpperCamelCase( __lowerCamelCase ): def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[Any] = tempfile.mkdtemp() __a : int = 8 # DPR tok __a : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , 'dpr_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_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] ) ) # BART tok __a : str = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __a : Optional[int] = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) __a : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : List[str] = {'unk_token': '<unk>'} __a : Dict = os.path.join(self.tmpdirname , 'bart_tokenizer' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['vocab_file'] ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowerCAmelCase ( self : str ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) ) def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Tuple = os.path.join(self.tmpdirname , 'rag_tokenizer' ) __a : Optional[Any] = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) __a : Optional[Any] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Optional[Any] = RagTokenizer.from_pretrained('facebook/rag-token-nq' ) __a : List[Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Any = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' ) __a : Union[str, Any] = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] __a : str = tokenizer(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
47
0
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging _snake_case : str = logging.get_logger(__name__) logging.set_verbosity_info() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): if "xprophetnet" in prophetnet_checkpoint_path: __snake_case : Any = XLMProphetNetForConditionalGenerationOld.from_pretrained(__lowerCamelCase ) __snake_case , __snake_case : Optional[Any] = XLMProphetNetForConditionalGeneration.from_pretrained( __lowerCamelCase , output_loading_info=__lowerCamelCase ) else: __snake_case : Optional[int] = ProphetNetForConditionalGenerationOld.from_pretrained(__lowerCamelCase ) __snake_case , __snake_case : Dict = ProphetNetForConditionalGeneration.from_pretrained( __lowerCamelCase , output_loading_info=__lowerCamelCase ) __snake_case : Union[str, Any] = ["key_proj", "value_proj", "query_proj"] __snake_case : Tuple = { "self_attn": "ngram_self_attn", "cross_attn": "encoder_attn", "cross_attn_layer_norm": "encoder_attn_layer_norm", "feed_forward_layer_norm": "final_layer_norm", "feed_forward": "", "intermediate": "fc1", "output": "fc2", "key_proj": "k_proj", "query_proj": "q_proj", "value_proj": "v_proj", "word_embeddings": "embed_tokens", "embeddings_layer_norm": "emb_layer_norm", "relative_pos_embeddings": "relative_linear", "ngram_embeddings": "ngram_input_embed", "position_embeddings": "embed_positions", } for key in loading_info["missing_keys"]: __snake_case : Optional[Any] = key.split("." ) if attributes[0] == "lm_head": __snake_case : Dict = prophet __snake_case : Tuple = prophet_old else: __snake_case : str = prophet.prophetnet __snake_case : Any = prophet_old.model __snake_case : Any = False for attribute in attributes: if attribute in mapping: __snake_case : Optional[int] = mapping[attribute] if not hasattr(__lowerCamelCase , __lowerCamelCase ) and len(__lowerCamelCase ) > 0: __snake_case : List[str] = attribute elif hasattr(__lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" __snake_case : Dict = old_model.weight logger.info(F'{attribute} is initialized.' ) __snake_case : int = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" __snake_case : int = old_model.bias logger.info(F'{attribute} is initialized' ) __snake_case : Dict = True break elif attribute in special_keys and hasattr(__lowerCamelCase , "in_proj_weight" ): __snake_case : Any = old_model.in_proj_weight.shape[0] // 3 __snake_case : Dict = getattr(__lowerCamelCase , __lowerCamelCase ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": __snake_case : Any = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) __snake_case : Tuple = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": __snake_case : str = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) __snake_case : List[Any] = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": __snake_case : List[Any] = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) __snake_case : Optional[Any] = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) __snake_case : int = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_1_2, "We want 512 position_embeddings." __snake_case : Tuple = nn.Parameter(old_model.embed_positions.weight[:5_1_2, :] ) __snake_case : List[str] = True break if attribute.isdigit(): __snake_case : List[str] = model[int(__lowerCamelCase )] __snake_case : int = old_model[int(__lowerCamelCase )] else: __snake_case : Optional[int] = getattr(__lowerCamelCase , __lowerCamelCase ) if old_attribute == "": __snake_case : Optional[Any] = old_model else: if not hasattr(__lowerCamelCase , __lowerCamelCase ): raise ValueError(F'{old_model} does not have {old_attribute}' ) __snake_case : str = getattr(__lowerCamelCase , __lowerCamelCase ) if not is_key_init: raise ValueError(F'{key} was not correctly initialized!' ) print(F'Saving model to {pytorch_dump_folder_path}' ) prophet.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": _snake_case : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--prophetnet_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case : int = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
81
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''spiece.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } SCREAMING_SNAKE_CASE__ = {'''bert_for_seq_generation''': 512} class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : int = ['''input_ids''', '''attention_mask'''] def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : Any="<unk>" , SCREAMING_SNAKE_CASE__ : int="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="<::::>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : int = vocab_file __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): '''simple docstring''' __a : Union[str, Any] = self.__dict__.copy() __a : Any = None return state def __setstate__( self : int , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' __a : str = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : str = {} __a : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' __a : int = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Optional[Any] = [] __a : Optional[int] = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token __a : Dict = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Tuple = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
"""simple docstring""" from sklearn.metrics import fa_score import datasets lowerCamelCase = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ lowerCamelCase = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ lowerCamelCase = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): '''simple docstring''' def lowercase__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def lowercase__ ( self : Tuple , _UpperCAmelCase : Dict , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Tuple=None , _UpperCAmelCase : Dict=1 , _UpperCAmelCase : List[Any]="binary" , _UpperCAmelCase : int=None ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = fa_score( _UpperCAmelCase , _UpperCAmelCase , labels=_UpperCAmelCase , pos_label=_UpperCAmelCase , average=_UpperCAmelCase , sample_weight=_UpperCAmelCase ) return {"f1": float(_UpperCAmelCase ) if score.size == 1 else score}
82
from ..utils import DummyObject, requires_backends class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Any = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : str , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Dict , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class _UpperCamelCase( metaclass=__lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __lowerCAmelCase ( cls : int , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' requires_backends(cls , ['torch', 'transformers', 'onnx'] )
47
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin 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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case : def __init__( self : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : int=3_2 , __lowerCAmelCase : int=3 , __lowerCAmelCase : Union[str, Any]=4 , __lowerCAmelCase : Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , __lowerCAmelCase : List[str]=[2, 2, 3, 2] , __lowerCAmelCase : int=True , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Optional[Any]=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : List[Any]=["stage2", "stage3", "stage4"] , __lowerCAmelCase : Union[str, Any]=[2, 3, 4] , __lowerCAmelCase : int=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : Optional[int] = image_size _lowerCamelCase : Union[str, Any] = num_channels _lowerCamelCase : List[str] = num_stages _lowerCamelCase : Union[str, Any] = hidden_sizes _lowerCamelCase : int = depths _lowerCamelCase : str = is_training _lowerCamelCase : Dict = use_labels _lowerCamelCase : Union[str, Any] = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = num_labels _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : int = out_features _lowerCamelCase : str = out_indices _lowerCamelCase : str = scope def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCamelCase : Optional[int] = None if self.use_labels: _lowerCamelCase : Any = ids_tensor([self.batch_size] , self.num_labels ) _lowerCamelCase : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = ConvNextModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _lowerCamelCase : int = None _lowerCamelCase : Optional[int] = ConvNextBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[int] = config_and_inputs _lowerCamelCase : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : Dict = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) snake_case__ : Dict = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) snake_case__ : Optional[int] = True snake_case__ : Optional[int] = False snake_case__ : Optional[int] = False snake_case__ : Union[str, Any] = False snake_case__ : Tuple = False def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = ConvNextModelTester(self ) _lowerCamelCase : Tuple = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return @unittest.skip(reason='''ConvNext does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" pass @unittest.skip(reason='''ConvNext does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass @unittest.skip(reason='''ConvNext does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : List[str] = model_class(__lowerCAmelCase ) _lowerCamelCase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : int = [*signature.parameters.keys()] _lowerCamelCase : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" def check_hidden_states_output(__lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict ): _lowerCamelCase : List[str] = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): _lowerCamelCase : Tuple = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) _lowerCamelCase : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCamelCase : Tuple = self.model_tester.num_stages self.assertEqual(len(__lowerCAmelCase ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Union[str, Any] = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = ConvNextModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Dict = ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''' ).to(__lowerCAmelCase ) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Union[str, Any] = prepare_img() _lowerCamelCase : Tuple = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Dict = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : str = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : int = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) ) @require_torch class __snake_case ( unittest.TestCase , _lowercase): snake_case__ : Any = (ConvNextBackbone,) if is_torch_available() else () snake_case__ : Union[str, Any] = ConvNextConfig snake_case__ : int = False def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextModelTester(self )
83
import math from datetime import datetime, timedelta def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Union[str, Any] = year % 1_9 __a : int = year % 4 __a : Optional[int] = year % 7 __a : Dict = math.floor(year / 1_0_0 ) __a : Optional[Any] = math.floor((1_3 + 8 * leap_day_inhibits) / 2_5 ) __a : Union[str, Any] = leap_day_inhibits / 4 __a : str = ( 1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 3_0 __a : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __a : List[Any] = (1_9 * metonic_cycle + secular_moon_shift) % 3_0 # PHM -> Paschal Full Moon __a : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 2_9 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_9 ) elif days_to_add == 2_8 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ , 4 , 1_8 ) else: return datetime(lowerCamelCase_ , 3 , 2_2 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): SCREAMING_SNAKE_CASE__ = '''will be''' if year > datetime.now().year else '''was''' print(F"Easter in {year} {tense} {gauss_easter(year)}")
47
0
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: UpperCAmelCase = None UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } UpperCAmelCase = { '''facebook/mbart-large-en-ro''': 1024, '''facebook/mbart-large-cc25''': 1024, } # fmt: off UpperCAmelCase = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : int = ["""input_ids""", """attention_mask"""] _UpperCamelCase : List[Any] = MBartTokenizer _UpperCamelCase : List[int] = [] _UpperCamelCase : List[int] = [] def __init__( self , snake_case=None , snake_case=None , snake_case="<s>" , snake_case="</s>" , snake_case="</s>" , snake_case="<s>" , snake_case="<unk>" , snake_case="<pad>" , snake_case="<mask>" , snake_case=None , snake_case=None , snake_case=None , **snake_case , ): # Mask token behave like a normal word, i.e. include the space before it lowercase = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token super().__init__( vocab_file=snake_case , tokenizer_file=snake_case , bos_token=snake_case , eos_token=snake_case , sep_token=snake_case , cls_token=snake_case , unk_token=snake_case , pad_token=snake_case , mask_token=snake_case , src_lang=snake_case , tgt_lang=snake_case , additional_special_tokens=snake_case , **snake_case , ) lowercase = vocab_file lowercase = False if not self.vocab_file else True lowercase = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) lowercase = { lang_code: self.convert_tokens_to_ids(snake_case ) for lang_code in FAIRSEQ_LANGUAGE_CODES } lowercase = src_lang if src_lang is not None else 'en_XX' lowercase = self.convert_tokens_to_ids(self._src_lang ) lowercase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def SCREAMING_SNAKE_CASE__ ( self ): return self._src_lang @src_lang.setter def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ): lowercase = [self.sep_token_id] lowercase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case , **snake_case ): if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) lowercase = src_lang lowercase = self(snake_case , add_special_tokens=snake_case , return_tensors=snake_case , **snake_case ) lowercase = self.convert_tokens_to_ids(snake_case ) lowercase = tgt_lang_id return inputs def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = "en_XX" , snake_case = None , snake_case = "ro_RO" , **snake_case , ): lowercase = src_lang lowercase = tgt_lang return super().prepare_seqaseq_batch(snake_case , snake_case , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def SCREAMING_SNAKE_CASE__ ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = self.convert_tokens_to_ids(snake_case ) lowercase = [] lowercase = [self.eos_token_id, self.cur_lang_code] lowercase = self.convert_ids_to_tokens(self.prefix_tokens ) lowercase = self.convert_ids_to_tokens(self.suffix_tokens ) lowercase = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = self.convert_tokens_to_ids(snake_case ) lowercase = [] lowercase = [self.eos_token_id, self.cur_lang_code] lowercase = self.convert_ids_to_tokens(self.prefix_tokens ) lowercase = self.convert_ids_to_tokens(self.suffix_tokens ) lowercase = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(snake_case ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory.''' ) return lowercase = os.path.join( snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case ): copyfile(self.vocab_file , snake_case ) return (out_vocab_file,)
84
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = '''informer''' __SCREAMING_SNAKE_CASE : List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "student_t" , SCREAMING_SNAKE_CASE__ : str = "nll" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : List[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : int = 6_4 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 3_2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.05 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str = "prob" , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Tuple , ): '''simple docstring''' __a : Dict = prediction_length __a : Tuple = context_length or prediction_length __a : Tuple = distribution_output __a : Tuple = loss __a : str = input_size __a : Dict = num_time_features __a : Optional[int] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __a : str = scaling __a : Tuple = num_dynamic_real_features __a : int = num_static_real_features __a : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __a : Optional[Any] = cardinality else: __a : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE__ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __a : int = embedding_dimension else: __a : List[Any] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] __a : int = num_parallel_samples # Transformer architecture configuration __a : str = input_size * len(self.lags_sequence ) + self._number_of_features __a : Optional[int] = d_model __a : Union[str, Any] = encoder_attention_heads __a : int = decoder_attention_heads __a : Any = encoder_ffn_dim __a : Union[str, Any] = decoder_ffn_dim __a : List[Any] = encoder_layers __a : Optional[int] = decoder_layers __a : int = dropout __a : Optional[Any] = attention_dropout __a : Dict = activation_dropout __a : Union[str, Any] = encoder_layerdrop __a : Optional[int] = decoder_layerdrop __a : List[str] = activation_function __a : str = init_std __a : Optional[int] = use_cache # Informer __a : Union[str, Any] = attention_type __a : str = sampling_factor __a : Dict = distil super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib SCREAMING_SNAKE_CASE__ : List[Any] = get_logger() SCREAMING_SNAKE_CASE__ : Optional[dict] = None class snake_case ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): def __init__( self : Any , a_ : Dict=None , a_ : Dict=None , **a_ : Optional[int] )-> Tuple: """simple docstring""" super().__init__(features=a_ ) import jax from jaxlib.xla_client import Device if isinstance(a_ , a_ ): raise ValueError( F'''Expected {device} to be a `str` not {type(a_ )}, as `jaxlib.xla_extension.Device` ''' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = device if isinstance(a_ , a_ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE__ : List[Any] = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F'''Device with string identifier {self.device} not listed among the available ''' F'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' F'''device: {str(jax.devices()[0] )}.''' ) SCREAMING_SNAKE_CASE__ : Tuple = str(jax.devices()[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp_array_kwargs @staticmethod def __lowercase( )-> Dict[str, "jaxlib.xla_extension.Device"]: """simple docstring""" import jax return {str(a_ ): device for device in jax.devices()} def __lowercase( self : str , a_ : Dict )-> List[str]: """simple docstring""" import jax import jax.numpy as jnp if isinstance(a_ , a_ ) and column: if all( isinstance(a_ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(a_ , axis=0 ) return column def __lowercase( self : int , a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" import jax import jax.numpy as jnp if isinstance(a_ , (str, bytes, type(a_ )) ): return value elif isinstance(a_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE__ : Optional[int] = {} if isinstance(a_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: SCREAMING_SNAKE_CASE__ : str = {'dtype': jnp.intaa} else: SCREAMING_SNAKE_CASE__ : List[Any] = {'dtype': jnp.intaa} elif isinstance(a_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE__ : Optional[int] = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(a_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE__ : Optional[int] = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(a_ , **{**default_dtype, **self.jnp_array_kwargs} ) def __lowercase( self : Optional[Any] , a_ : Any )-> Union[str, Any]: """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(a_ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(a_ , '__array__' ) and not isinstance(a_ , jax.Array ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(a_ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(a_ ) for substruct in data_struct] ) elif isinstance(a_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(a_ ) for substruct in data_struct] ) return self._tensorize(a_ ) def __lowercase( self : Union[str, Any] , a_ : dict )-> List[str]: """simple docstring""" return map_nested(self._recursive_tensorize , a_ , map_list=a_ ) def __lowercase( self : Dict , a_ : pa.Table )-> Mapping: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.numpy_arrow_extractor().extract_row(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.python_features_decoder.decode_row(a_ ) return self.recursive_tensorize(a_ ) def __lowercase( self : Any , a_ : pa.Table )-> "jax.Array": """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.numpy_arrow_extractor().extract_column(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.python_features_decoder.decode_column(a_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE__ : Dict = self.recursive_tensorize(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self._consolidate(a_ ) return column def __lowercase( self : Optional[int] , a_ : pa.Table )-> Mapping: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.numpy_arrow_extractor().extract_batch(a_ ) SCREAMING_SNAKE_CASE__ : str = self.python_features_decoder.decode_batch(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.recursive_tensorize(a_ ) for column_name in batch: SCREAMING_SNAKE_CASE__ : Tuple = self._consolidate(batch[column_name] ) return batch
85
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE : Union[str, Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : List[str] = 1_0, 0.0 __a : Dict = self.dummy_model() __a : str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __a : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config(steps_offset=1 ) __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 1_0, 5_0] , [1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for t, eta in zip([1, 1_0, 4_9] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 , 4_0_0 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 , 9_6_0 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 , 4_8_6 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 , 9_9_8 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config() __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : Any = 1_0, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = self.dummy_model() __a : int = self.dummy_sample_deter __a : List[Any] = self.dummy_sample_deter + 0.1 __a : List[str] = self.dummy_sample_deter - 0.1 __a : Optional[Any] = samplea.shape[0] __a : Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) __a : Union[str, Any] = torch.arange(SCREAMING_SNAKE_CASE__ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE__ ) __a : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a : int = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE__ ) __a : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : List[str] = self.full_loop() __a : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : Dict = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
47
0
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() __a :Any = logging.get_logger(__name__) __a :int = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn.grep_linear': 'encoder.layers.*.attention.gru_rel_pos_linear', 'self_attn.relative_attention_bias': 'encoder.layers.*.attention.rel_attn_embed', 'self_attn.grep_a': 'encoder.layers.*.attention.gru_rel_pos_const', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'ctc_proj', 'mask_emb': 'masked_spec_embed', } __a :Tuple = [ 'ctc_proj', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def __snake_case ( __UpperCamelCase : List[str] ,__UpperCamelCase : List[Any] ,__UpperCamelCase : Dict ,__UpperCamelCase : Any ,__UpperCamelCase : Optional[int] ): """simple docstring""" for attribute in key.split("." ): A_ = getattr(__UpperCamelCase ,__UpperCamelCase ) if weight_type is not None: A_ = getattr(__UpperCamelCase ,__UpperCamelCase ).shape else: A_ = 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": A_ = value elif weight_type == "weight_g": A_ = value elif weight_type == "weight_v": A_ = value elif weight_type == "bias": A_ = value else: A_ = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def __snake_case ( __UpperCamelCase : Optional[int] ,__UpperCamelCase : Optional[Any] ): """simple docstring""" A_ = [] A_ = fairseq_model.state_dict() A_ = hf_model.feature_extractor for name, value in fairseq_dict.items(): A_ = False if "conv_layers" in name: load_conv_layer( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,hf_model.config.feat_extract_norm == "group" ,) A_ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: A_ = True if "*" in mapped_key: A_ = name.split(__UpperCamelCase )[0].split("." )[-2] A_ = mapped_key.replace("*" ,__UpperCamelCase ) if "weight_g" in name: A_ = "weight_g" elif "weight_v" in name: A_ = "weight_v" elif "bias" in name and "relative_attention_bias" not in name: A_ = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj A_ = "weight" else: A_ = None set_recursively(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) continue if not is_used: unused_weights.append(__UpperCamelCase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def __snake_case ( __UpperCamelCase : Optional[int] ,__UpperCamelCase : Dict ,__UpperCamelCase : List[str] ,__UpperCamelCase : Union[str, Any] ,__UpperCamelCase : Optional[int] ): """simple docstring""" A_ = full_name.split("conv_layers." )[-1] A_ = name.split("." ) A_ = int(items[0] ) A_ = 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.''' ) A_ = 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.''' ) A_ = 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." ) A_ = 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.''' ) A_ = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__UpperCamelCase ) @torch.no_grad() def __snake_case ( __UpperCamelCase : Dict ,__UpperCamelCase : str ,__UpperCamelCase : int=None ): """simple docstring""" A_ = torch.load(__UpperCamelCase ) A_ = WavLMConfigOrig(checkpoint["cfg"] ) A_ = WavLMOrig(__UpperCamelCase ) model.load_state_dict(checkpoint["model"] ) model.eval() if config_path is not None: A_ = WavLMConfig.from_pretrained(__UpperCamelCase ) else: A_ = WavLMConfig() A_ = WavLMModel(__UpperCamelCase ) recursively_load_weights(__UpperCamelCase ,__UpperCamelCase ) hf_wavlm.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": __a :List[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __a :Optional[int] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
def UpperCAmelCase__ ( lowerCamelCase_ : list[int] , lowerCamelCase_ : list[int] ): # Check if the input is valid if not len(lowerCamelCase_ ) == len(lowerCamelCase_ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __a , __a , __a : Optional[Any] = equationa __a , __a , __a : Optional[int] = equationa # Calculate the determinants of the matrices __a : str = aa * ba - aa * ba __a : Tuple = ca * ba - ca * ba __a : Union[str, Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __a : Any = determinant_x / determinant __a : Optional[Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
47
0
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
47
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = """▁""" UpperCAmelCase = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase = { """facebook/xglm-564M""": 2048, } class lowercase__ ( A_ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['''input_ids''', '''attention_mask'''] def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="<unk>" , SCREAMING_SNAKE_CASE="<pad>" , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> None: _lowerCamelCase : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer _lowerCamelCase : List[str] = 7 _lowerCamelCase : List[str] = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] _lowerCamelCase : Union[str, Any] = kwargs.get("""additional_special_tokens""" , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _lowerCamelCase : List[Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token _lowerCamelCase : List[Any] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} _lowerCamelCase : str = len(self.sp_model) _lowerCamelCase : List[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self) -> Optional[Any]: _lowerCamelCase : str = self.__dict__.copy() _lowerCamelCase : Any = None _lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs"""): _lowerCamelCase : Optional[int] = {} _lowerCamelCase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> List[int]: if token_ids_a is None: return [self.sep_token_id] + token_ids_a _lowerCamelCase : List[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE , token_ids_a=SCREAMING_SNAKE_CASE , already_has_special_tokens=SCREAMING_SNAKE_CASE) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> List[int]: _lowerCamelCase : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def UpperCamelCase_ ( self) -> List[str]: return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE , out_type=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Optional[int]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _lowerCamelCase : List[Any] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> int: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[Any]: _lowerCamelCase : Any = """""".join(SCREAMING_SNAKE_CASE).replace(SCREAMING_SNAKE_CASE , """ """).strip() return out_string def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return _lowerCamelCase : Tuple = os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE , """wb""") as fi: _lowerCamelCase : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE) return (out_vocab_file,)
88
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
47
0
def UpperCamelCase_( lowerCamelCase_ = 100 ) -> int: _lowercase : List[Any] = set() _lowercase : Tuple = 0 _lowercase : Tuple = n + 1 # maximum limit for a in range(2 , lowerCamelCase_ ): for b in range(2 , lowerCamelCase_ ): _lowercase : List[str] = a**b # calculates the current power collect_powers.add(lowerCamelCase_ ) # adds the result to the set return len(lowerCamelCase_ ) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
89
from string import ascii_lowercase, ascii_uppercase def UpperCAmelCase__ ( lowerCamelCase_ : str ): if not sentence: return "" __a : Union[str, Any] = dict(zip(lowerCamelCase_ , lowerCamelCase_ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
47
0
'''simple docstring''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _snake_case ( A , A , A ) -> List[Any]: lowerCAmelCase__ = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, oder?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] lowerCAmelCase__ = { '''ru-en''': ['''[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)''', '''39.20'''], '''en-ru''': ['''[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)''', '''33.47'''], '''en-de''': ['''[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)''', '''42.83'''], '''de-en''': ['''[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)''', '''41.35'''], } lowerCAmelCase__ = F"""{src_lang}-{tgt_lang}""" lowerCAmelCase__ = F""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR's WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) """ os.makedirs(A , exist_ok=A ) lowerCAmelCase__ = os.path.join(A , '''README.md''' ) print(F"""Generating {path}""" ) with open(A , '''w''' , encoding='''utf-8''' ) as f: f.write(A ) # make sure we are under the root of the project __UpperCAmelCase = Path(__file__).resolve().parent.parent.parent __UpperCAmelCase = repo_dir / '''model_cards''' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = model_name.split('''-''') __UpperCAmelCase = model_cards_dir / '''facebook''' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
90
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''sew-d''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=("p2c", "c2p") , SCREAMING_SNAKE_CASE__ : str="layer_norm" , SCREAMING_SNAKE_CASE__ : Tuple="gelu_python" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-7 , SCREAMING_SNAKE_CASE__ : Any=1e-5 , SCREAMING_SNAKE_CASE__ : Optional[int]="group" , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : str=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2_8 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[Any]=0.05 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]="mean" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : str=2_5_6 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = hidden_size __a : Optional[Any] = feat_extract_norm __a : List[str] = feat_extract_activation __a : Dict = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = list(SCREAMING_SNAKE_CASE__ ) __a : List[str] = list(SCREAMING_SNAKE_CASE__ ) __a : int = conv_bias __a : Tuple = num_conv_pos_embeddings __a : List[str] = num_conv_pos_embedding_groups __a : Optional[Any] = len(self.conv_dim ) __a : Union[str, Any] = num_hidden_layers __a : Optional[Any] = intermediate_size __a : Union[str, Any] = squeeze_factor __a : List[Any] = max_position_embeddings __a : Tuple = position_buckets __a : Optional[int] = share_att_key __a : List[str] = relative_attention __a : Any = norm_rel_ebd __a : Any = list(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = hidden_act __a : str = num_attention_heads __a : Union[str, Any] = hidden_dropout __a : Optional[int] = attention_dropout __a : List[str] = activation_dropout __a : int = feat_proj_dropout __a : int = final_dropout __a : Dict = layer_norm_eps __a : Tuple = feature_layer_norm_eps __a : str = initializer_range __a : Tuple = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : Tuple = apply_spec_augment __a : Optional[Any] = mask_time_prob __a : Any = mask_time_length __a : List[str] = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Tuple = mask_feature_length __a : Any = mask_feature_min_masks # ctc loss __a : Optional[int] = ctc_loss_reduction __a : List[Any] = ctc_zero_infinity # sequence classification __a : Dict = use_weighted_layer_sum __a : Optional[Any] = classifier_proj_size @property def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
47
0
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int _lowercase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowerCAmelCase_ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase: Optional[datasets.Features] = None def _snake_case ( snake_case__ : "pyspark.sql.DataFrame" , snake_case__ : List[int] , ): import pyspark def generate_fn(): A = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: A = df_with_partition_id.select('*' ).where(F'part_id = {partition_id}' ).drop('part_id' ) A = partition_df.collect() A = 0 for row in rows: yield F'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class lowerCAmelCase_ ( _BaseExamplesIterable ): '''simple docstring''' def __init__( self : str ,A_ : "pyspark.sql.DataFrame" ,A_ : Optional[int]=None ,) -> str: A = df A = partition_order or range(self.df.rdd.getNumPartitions() ) A = _generate_iterable_examples(self.df ,self.partition_order ) def __iter__( self : Dict ) -> Dict: yield from self.generate_examples_fn() def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : np.random.Generator ) -> "SparkExamplesIterable": A = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(A_ ) return SparkExamplesIterable(self.df ,partition_order=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : int ,A_ : int ) -> "SparkExamplesIterable": A = self.split_shard_indices_by_worker(A_ ,A_ ) return SparkExamplesIterable(self.df ,partition_order=A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: return len(self.partition_order ) class lowerCAmelCase_ ( datasets.DatasetBuilder ): '''simple docstring''' _lowerCamelCase: Any = SparkConfig def __init__( self : Union[str, Any] ,A_ : "pyspark.sql.DataFrame" ,A_ : str = None ,A_ : str = None ,**A_ : Union[str, Any] ,) -> Union[str, Any]: import pyspark A = pyspark.sql.SparkSession.builder.getOrCreate() A = df A = working_dir super().__init__( cache_dir=A_ ,config_name=str(self.df.semanticHash() ) ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: # Returns the path of the created file. def create_cache_and_write_probe(A_ : int ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir ,exist_ok=A_ ) A = os.path.join(self._cache_dir ,'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(A_ ,'a' ) return [probe_file] if self._spark.conf.get('spark.master' ,'' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: A = ( self._spark.sparkContext.parallelize(range(1 ) ,1 ).mapPartitions(A_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return datasets.DatasetInfo(features=self.config.features ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : datasets.download.download_manager.DownloadManager ) -> Any: return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: import pyspark def get_arrow_batch_size(A_ : Tuple ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) A = self.df.count() A = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. A = ( self.df.limit(A_ ) .repartition(1 ) .mapInArrow(A_ ,'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) A = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. A = min(A_ ,int(approx_total_size / max_shard_size ) ) A = self.df.repartition(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : str ,A_ : str ,A_ : int ,) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark A = ParquetWriter if file_format == 'parquet' else ArrowWriter A = os.path.join(self._working_dir ,os.path.basename(A_ ) ) if self._working_dir else fpath A = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. A = self.config.features A = self._writer_batch_size A = self._fs.storage_options def write_arrow(A_ : List[Any] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. A = pyspark.TaskContext().taskAttemptId() A = next(A_ ,A_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] ,names=['task_id', 'num_examples', 'num_bytes'] ,) A = 0 A = writer_class( features=A_ ,path=working_fpath.replace('SSSSS' ,F'{shard_id:05d}' ).replace('TTTTT' ,F'{task_id:05d}' ) ,writer_batch_size=A_ ,storage_options=A_ ,embed_local_files=A_ ,) A = pa.Table.from_batches([first_batch] ) writer.write_table(A_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: A , A = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] ,names=['task_id', 'num_examples', 'num_bytes'] ,) shard_id += 1 A = writer_class( features=writer._features ,path=working_fpath.replace('SSSSS' ,F'{shard_id:05d}' ).replace('TTTTT' ,F'{task_id:05d}' ) ,writer_batch_size=A_ ,storage_options=A_ ,embed_local_files=A_ ,) A = pa.Table.from_batches([batch] ) writer.write_table(A_ ) if writer._num_bytes > 0: A , A = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] ,names=['task_id', 'num_examples', 'num_bytes'] ,) if working_fpath != fpath: for file in os.listdir(os.path.dirname(A_ ) ): A = os.path.join(os.path.dirname(A_ ) ,os.path.basename(A_ ) ) shutil.move(A_ ,A_ ) A = ( self.df.mapInArrow(A_ ,'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) ,pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) ,pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) ,pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) ,) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : "datasets.SplitGenerator" ,A_ : str = "arrow" ,A_ : Optional[Union[str, int]] = None ,A_ : Optional[int] = None ,**A_ : List[str] ,) -> Union[str, Any]: self._validate_cache_dir() A = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(A_ ) A = not is_remote_filesystem(self._fs ) A = os.path.join if is_local else posixpath.join A = '-TTTTT-SSSSS-of-NNNNN' A = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' A = path_join(self._output_dir ,A_ ) A = 0 A = 0 A = 0 A = [] A = [] for task_id, content in self._prepare_split_single(A_ ,A_ ,A_ ): ( ( A ) , ( A ) , ( A ) , ( A ) , ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(A_ ) A = total_num_examples A = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: A = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. A = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( A_ : int ,A_ : int ,A_ : int ,): rename( A_ ,fpath.replace('SSSSS' ,F'{shard_id:05d}' ).replace('TTTTT' ,F'{task_id:05d}' ) ,fpath.replace('TTTTT-SSSSS' ,F'{global_shard_id:05d}' ).replace('NNNNN' ,F'{total_shards:05d}' ) ,) A = [] A = 0 for i in range(len(A_ ) ): A , A = task_id_and_num_shards[i] for shard_id in range(A_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(A_ ,len(A_ ) ).map(lambda A_ : _rename_shard(*A_ ) ).collect() else: # don't use any pattern A = 0 A = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' ,F'{shard_id:05d}' ).replace('TTTTT' ,F'{task_id:05d}' ) ,fpath.replace(A_ ,'' ) ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : "datasets.SplitGenerator" ,) -> SparkExamplesIterable: return SparkExamplesIterable(self.df )
91
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor UpperCamelCase_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowercase__ ): def __init__( self : Optional[int] , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Tuple ): '''simple docstring''' warnings.warn( '''The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DPTImageProcessor instead.''' , UpperCAmelCase__ , ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
92
from collections.abc import Sequence from queue import Queue class _UpperCamelCase: def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Tuple=None ): '''simple docstring''' __a : Tuple = start __a : Dict = end __a : List[str] = val __a : List[Any] = (start + end) // 2 __a : Optional[Any] = left __a : List[str] = right def __repr__( self : Dict ): '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class _UpperCamelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Sequence , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Tuple = collection __a : Dict = function if self.collection: __a : int = self._build_tree(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.collection[start] ) __a : Tuple = (start + end) // 2 __a : Optional[int] = self._build_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Tuple = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE__ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if node.start == i and node.end == i: __a : Optional[Any] = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = self.fn(node.left.val , node.right.val ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE__ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE__ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' if self.root is not None: __a : Tuple = Queue() queue.put(self.root ) while not queue.empty(): __a : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) SCREAMING_SNAKE_CASE__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
47
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer __A = logging.get_logger(__name__) __A = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __A = { """vocab_file""": { """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt""", """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt""", """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/vocab.txt""", """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/vocab.txt""", """bert-base-multilingual-uncased""": ( """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt""" ), """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt""", """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt""", """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt""", """bert-large-uncased-whole-word-masking""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt""" ), """bert-large-cased-whole-word-masking""": ( """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt""" ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt""" ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt""" ), """bert-base-cased-finetuned-mrpc""": ( """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt""" ), """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt""", """bert-base-german-dbmdz-uncased""": ( """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt""" ), """TurkuNLP/bert-base-finnish-cased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt""" ), """TurkuNLP/bert-base-finnish-uncased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt""" ), """wietsedv/bert-base-dutch-cased""": ( """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json""", """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json""", """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json""", """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json""", """bert-base-multilingual-uncased""": ( """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json""" ), """bert-base-multilingual-cased""": ( """https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json""" ), """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json""", """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json""", """bert-large-uncased-whole-word-masking""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json""" ), """bert-large-cased-whole-word-masking""": ( """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json""" ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json""" ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json""" ), """bert-base-cased-finetuned-mrpc""": ( """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json""" ), """bert-base-german-dbmdz-cased""": ( """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json""" ), """bert-base-german-dbmdz-uncased""": ( """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json""" ), """TurkuNLP/bert-base-finnish-cased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json""" ), """TurkuNLP/bert-base-finnish-uncased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json""" ), """wietsedv/bert-base-dutch-cased""": ( """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json""" ), }, } __A = { """bert-base-uncased""": 512, """bert-large-uncased""": 512, """bert-base-cased""": 512, """bert-large-cased""": 512, """bert-base-multilingual-uncased""": 512, """bert-base-multilingual-cased""": 512, """bert-base-chinese""": 512, """bert-base-german-cased""": 512, """bert-large-uncased-whole-word-masking""": 512, """bert-large-cased-whole-word-masking""": 512, """bert-large-uncased-whole-word-masking-finetuned-squad""": 512, """bert-large-cased-whole-word-masking-finetuned-squad""": 512, """bert-base-cased-finetuned-mrpc""": 512, """bert-base-german-dbmdz-cased""": 512, """bert-base-german-dbmdz-uncased""": 512, """TurkuNLP/bert-base-finnish-cased-v1""": 512, """TurkuNLP/bert-base-finnish-uncased-v1""": 512, """wietsedv/bert-base-dutch-cased""": 512, } __A = { """bert-base-uncased""": {"""do_lower_case""": True}, """bert-large-uncased""": {"""do_lower_case""": True}, """bert-base-cased""": {"""do_lower_case""": False}, """bert-large-cased""": {"""do_lower_case""": False}, """bert-base-multilingual-uncased""": {"""do_lower_case""": True}, """bert-base-multilingual-cased""": {"""do_lower_case""": False}, """bert-base-chinese""": {"""do_lower_case""": False}, """bert-base-german-cased""": {"""do_lower_case""": False}, """bert-large-uncased-whole-word-masking""": {"""do_lower_case""": True}, """bert-large-cased-whole-word-masking""": {"""do_lower_case""": False}, """bert-large-uncased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": True}, """bert-large-cased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": False}, """bert-base-cased-finetuned-mrpc""": {"""do_lower_case""": False}, """bert-base-german-dbmdz-cased""": {"""do_lower_case""": False}, """bert-base-german-dbmdz-uncased""": {"""do_lower_case""": True}, """TurkuNLP/bert-base-finnish-cased-v1""": {"""do_lower_case""": False}, """TurkuNLP/bert-base-finnish-uncased-v1""": {"""do_lower_case""": True}, """wietsedv/bert-base-dutch-cased""": {"""do_lower_case""": False}, } class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :int = VOCAB_FILES_NAMES __magic_name__ :List[str] = PRETRAINED_VOCAB_FILES_MAP __magic_name__ :Union[str, Any] = PRETRAINED_INIT_CONFIGURATION __magic_name__ :int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ :Union[str, Any] = BertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) lowerCAmelCase__ :Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('strip_accents' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __UpperCAmelCase ) != tokenize_chinese_chars ): lowerCAmelCase__ :Tuple = getattr(__UpperCAmelCase , normalizer_state.pop('type' ) ) lowerCAmelCase__ :Optional[Any] = do_lower_case lowerCAmelCase__ :List[str] = strip_accents lowerCAmelCase__ :Optional[int] = tokenize_chinese_chars lowerCAmelCase__ :Tuple = normalizer_class(**__UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = do_lower_case def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' lowerCAmelCase__ :Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :Any = [self.sep_token_id] lowerCAmelCase__ :List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
93
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int SCREAMING_SNAKE_CASE__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _UpperCamelCase( datasets.BuilderConfig ): __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None def UpperCAmelCase__ ( lowerCamelCase_ : "pyspark.sql.DataFrame" , lowerCamelCase_ : List[int] , ): import pyspark def generate_fn(): __a : List[Any] = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __a : Optional[int] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __a : Optional[Any] = partition_df.collect() __a : Union[str, Any] = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _UpperCamelCase( _BaseExamplesIterable ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : Dict=None , ): '''simple docstring''' __a : List[str] = df __a : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) __a : List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : Tuple ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : np.random.Generator ): '''simple docstring''' __a : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return len(self.partition_order ) class _UpperCamelCase( datasets.DatasetBuilder ): __SCREAMING_SNAKE_CASE : List[str] = SparkConfig def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' import pyspark __a : int = pyspark.sql.SparkSession.builder.getOrCreate() __a : Optional[int] = df __a : List[Any] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__ : List[str] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE__ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __a : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE__ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : datasets.download.download_manager.DownloadManager ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE__ : int ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __a : List[str] = self.df.count() __a : Dict = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __a : List[str] = ( self.df.limit(SCREAMING_SNAKE_CASE__ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE__ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __a : Dict = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __a : Union[str, Any] = min(SCREAMING_SNAKE_CASE__ , int(approx_total_size / max_shard_size ) ) __a : int = self.df.repartition(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , ): '''simple docstring''' import pyspark __a : Any = ParquetWriter if file_format == 'parquet' else ArrowWriter __a : Union[str, Any] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) if self._working_dir else fpath __a : Optional[int] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __a : List[str] = self.config.features __a : int = self._writer_batch_size __a : Union[str, Any] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __a : Any = pyspark.TaskContext().taskAttemptId() __a : str = next(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __a : Any = 0 __a : List[str] = writer_class( features=SCREAMING_SNAKE_CASE__ , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __a , __a : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __a : Optional[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE__ , storage_options=SCREAMING_SNAKE_CASE__ , embed_local_files=SCREAMING_SNAKE_CASE__ , ) __a : Union[str, Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE__ ) if writer._num_bytes > 0: __a , __a : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ): __a : Any = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ) , os.path.basename(SCREAMING_SNAKE_CASE__ ) ) shutil.move(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE__ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , SCREAMING_SNAKE_CASE__ : str = "arrow" , SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' self._validate_cache_dir() __a : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = not is_remote_filesystem(self._fs ) __a : Optional[Any] = os.path.join if is_local else posixpath.join __a : Any = '-TTTTT-SSSSS-of-NNNNN' __a : Union[str, Any] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __a : Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE__ ) __a : Any = 0 __a : Dict = 0 __a : int = 0 __a : List[str] = [] __a : Optional[int] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE__ ) __a : List[str] = total_num_examples __a : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __a : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __a : Dict = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): rename( SCREAMING_SNAKE_CASE__ , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __a : Union[str, Any] = [] __a : List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a , __a : Union[str, Any] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE__ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ).map(lambda SCREAMING_SNAKE_CASE__ : _rename_shard(*SCREAMING_SNAKE_CASE__ ) ).collect() else: # don't use any pattern __a : List[Any] = 0 __a : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE__ , '' ) , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : "datasets.SplitGenerator" , ): '''simple docstring''' return SparkExamplesIterable(self.df )
47
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig SCREAMING_SNAKE_CASE = [ 'openmmlab/upernet-convnext-tiny', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring SCREAMING_SNAKE_CASE = 'UperNetConfig' class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : Union[int, Tuple[int, int]] , UpperCAmelCase : Union[int, Tuple[int, int], str] = 0 , UpperCAmelCase : bool = False , UpperCAmelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: '''simple docstring''' super().__init__() lowercase : List[Any] =nn.Convad( in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , bias=UpperCAmelCase , dilation=UpperCAmelCase , ) lowercase : Dict =nn.BatchNormad(UpperCAmelCase ) lowercase : Any =nn.ReLU() def A__ ( self : List[Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Tuple =self.conv(UpperCAmelCase ) lowercase : Tuple =self.batch_norm(UpperCAmelCase ) lowercase : Any =self.activation(UpperCAmelCase ) return output class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : int ) -> None: '''simple docstring''' super().__init__() lowercase : int =[ nn.AdaptiveAvgPoolad(UpperCAmelCase ), UperNetConvModule(UpperCAmelCase , UpperCAmelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(UpperCAmelCase ) , UpperCAmelCase ) def A__ ( self : Union[str, Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Tuple =input for layer in self.layers: lowercase : int =layer(UpperCAmelCase ) return hidden_state class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : Dict , UpperCAmelCase : Tuple[int, ...] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : bool ) -> None: '''simple docstring''' super().__init__() lowercase : List[str] =pool_scales lowercase : Optional[Any] =align_corners lowercase : List[str] =in_channels lowercase : Dict =channels lowercase : List[str] =[] for i, pool_scale in enumerate(UpperCAmelCase ): lowercase : List[str] =UperNetPyramidPoolingBlock(pool_scale=UpperCAmelCase , in_channels=UpperCAmelCase , channels=UpperCAmelCase ) self.blocks.append(UpperCAmelCase ) self.add_module(str(UpperCAmelCase ) , UpperCAmelCase ) def A__ ( self : List[Any] , UpperCAmelCase : torch.Tensor ) -> List[torch.Tensor]: '''simple docstring''' lowercase : Optional[int] =[] for ppm in self.blocks: lowercase : Optional[Any] =ppm(UpperCAmelCase ) lowercase : Any =nn.functional.interpolate( UpperCAmelCase , size=x.size()[2:] , mode='''bilinear''' , align_corners=self.align_corners ) ppm_outs.append(UpperCAmelCase ) return ppm_outs class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Union[str, Any] ) -> List[str]: '''simple docstring''' super().__init__() lowercase : Dict =config lowercase : str =config.pool_scales # e.g. (1, 2, 3, 6) lowercase : Optional[int] =in_channels lowercase : Tuple =config.hidden_size lowercase : int =False lowercase : List[str] =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module lowercase : Tuple =UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) lowercase : Optional[Any] =UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module lowercase : Tuple =nn.ModuleList() lowercase : Any =nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer lowercase : List[Any] =UperNetConvModule(UpperCAmelCase , self.channels , kernel_size=1 ) lowercase : Optional[int] =UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(UpperCAmelCase ) self.fpn_convs.append(UpperCAmelCase ) lowercase : str =UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def A__ ( self : str ) -> str: '''simple docstring''' self.apply(self._init_weights ) def A__ ( self : List[Any] , UpperCAmelCase : List[Any] ) -> List[str]: '''simple docstring''' if isinstance(UpperCAmelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def A__ ( self : List[Any] , UpperCAmelCase : Any ) -> Any: '''simple docstring''' lowercase : Optional[Any] =inputs[-1] lowercase : Tuple =[x] psp_outs.extend(self.psp_modules(UpperCAmelCase ) ) lowercase : List[Any] =torch.cat(UpperCAmelCase , dim=1 ) lowercase : str =self.bottleneck(UpperCAmelCase ) return output def A__ ( self : Optional[Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Union[str, Any] =[lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(UpperCAmelCase ) ) # build top-down path lowercase : Any =len(UpperCAmelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowercase : Optional[int] =laterals[i - 1].shape[2:] lowercase : Tuple =laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=UpperCAmelCase , mode='''bilinear''' , align_corners=self.align_corners ) # build outputs lowercase : Optional[Any] =[self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowercase : Optional[int] =nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode='''bilinear''' , align_corners=self.align_corners ) lowercase : Union[str, Any] =torch.cat(UpperCAmelCase , dim=1 ) lowercase : str =self.fpn_bottleneck(UpperCAmelCase ) lowercase : int =self.classifier(UpperCAmelCase ) return output class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : int , UpperCAmelCase : str , UpperCAmelCase : int = 2 , UpperCAmelCase : int = 3 , UpperCAmelCase : Union[int, Tuple[int, int]] = 1 ) -> None: '''simple docstring''' super().__init__() lowercase : int =config lowercase : Any =config.auxiliary_in_channels lowercase : int =config.auxiliary_channels lowercase : Dict =config.auxiliary_num_convs lowercase : List[Any] =config.auxiliary_concat_input lowercase : List[str] =in_index lowercase : Dict =(kernel_size // 2) * dilation lowercase : Union[str, Any] =[] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , dilation=UpperCAmelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , dilation=UpperCAmelCase ) ) if self.num_convs == 0: lowercase : int =nn.Identity() else: lowercase : Optional[Any] =nn.Sequential(*UpperCAmelCase ) if self.concat_input: lowercase : Tuple =UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=UpperCAmelCase , padding=kernel_size // 2 ) lowercase : List[Any] =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def A__ ( self : List[str] ) -> Tuple: '''simple docstring''' self.apply(self._init_weights ) def A__ ( self : Tuple , UpperCAmelCase : str ) -> Dict: '''simple docstring''' if isinstance(UpperCAmelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def A__ ( self : List[str] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Dict =encoder_hidden_states[self.in_index] lowercase : List[str] =self.convs(UpperCAmelCase ) if self.concat_input: lowercase : str =self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) lowercase : List[str] =self.classifier(UpperCAmelCase ) return output class UpperCAmelCase_ ( __A ): """simple docstring""" UpperCamelCase_ = UperNetConfig UpperCamelCase_ = '''pixel_values''' UpperCamelCase_ = True def A__ ( self : List[Any] , UpperCAmelCase : List[Any] ) -> Any: '''simple docstring''' if isinstance(UpperCAmelCase , UpperCAmelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def A__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def A__ ( self : Tuple , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any]=False ) -> List[str]: '''simple docstring''' if isinstance(UpperCAmelCase , UpperCAmelCase ): lowercase : List[Any] =value SCREAMING_SNAKE_CASE = r'\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , __A , ) class UpperCAmelCase_ ( __A ): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase : str ) -> Optional[int]: '''simple docstring''' super().__init__(UpperCAmelCase ) lowercase : Optional[int] =AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) lowercase : Optional[Any] =UperNetHead(UpperCAmelCase , in_channels=self.backbone.channels ) lowercase : Optional[int] =UperNetFCNHead(UpperCAmelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length''' ) ) @replace_return_docstrings(output_type=UpperCAmelCase , config_class=_CONFIG_FOR_DOC ) def A__ ( self : Dict , UpperCAmelCase : Optional[torch.Tensor] = None , UpperCAmelCase : Optional[bool] = None , UpperCAmelCase : Optional[bool] = None , UpperCAmelCase : Optional[torch.Tensor] = None , UpperCAmelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: '''simple docstring''' lowercase : Tuple =return_dict if return_dict is not None else self.config.use_return_dict lowercase : List[str] =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase : Any =output_attentions if output_attentions is not None else self.config.output_attentions lowercase : Union[str, Any] =self.backbone.forward_with_filtered_kwargs( UpperCAmelCase , output_hidden_states=UpperCAmelCase , output_attentions=UpperCAmelCase ) lowercase : List[Any] =outputs.feature_maps lowercase : Dict =self.decode_head(UpperCAmelCase ) lowercase : List[Any] =nn.functional.interpolate(UpperCAmelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=UpperCAmelCase ) lowercase : str =None if self.auxiliary_head is not None: lowercase : Optional[Any] =self.auxiliary_head(UpperCAmelCase ) lowercase : int =nn.functional.interpolate( UpperCAmelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=UpperCAmelCase ) lowercase : Optional[int] =None if labels is not None: if self.config.num_labels == 1: raise ValueError('''The number of labels should be greater than one''' ) else: # compute weighted loss lowercase : Optional[Any] =CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) lowercase : List[Any] =loss_fct(UpperCAmelCase , UpperCAmelCase ) lowercase : Any =loss_fct(UpperCAmelCase , UpperCAmelCase ) lowercase : List[str] =main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: lowercase : Tuple =(logits,) + outputs[1:] else: lowercase : Tuple =(logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=UpperCAmelCase , logits=UpperCAmelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
94
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : int ): # save results if os.path.exists(lowerCamelCase_ ): if os.path.exists(os.path.join(lowerCamelCase_ , 'config.json' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'config.json' ) ): os.remove(os.path.join(lowerCamelCase_ , 'config.json' ) ) if os.path.exists(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ): os.remove(os.path.join(lowerCamelCase_ , 'pytorch_model.bin' ) ) else: os.makedirs(lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) def UpperCAmelCase__ ( lowerCamelCase_ : int , lowerCamelCase_ : Any=False ): __a : Dict = 2 if unlogit: __a : Optional[Any] = torch.pow(lowerCamelCase_ , lowerCamelCase_ ) __a : Any = p * torch.log(lowerCamelCase_ ) __a : Union[str, Any] = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ ( lowerCamelCase_ : Any ): logger.info('lv, h >\t' + '\t'.join(f'''{x + 1}''' for x in range(len(lowerCamelCase_ ) ) ) ) for row in range(len(lowerCamelCase_ ) ): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(f'''layer {row + 1}:\t''' + '\t'.join(f'''{x:d}''' for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : List[Any]=False ): __a , __a : Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads __a : str = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) __a : int = torch.zeros(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) if head_mask is None: __a : Union[str, Any] = torch.ones(lowerCamelCase_ , lowerCamelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCamelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __a : Any = None __a : Optional[int] = 0.0 __a : Optional[Any] = 0.0 for step, inputs in enumerate(tqdm(lowerCamelCase_ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __a : Dict = tuple(t.to(args.device ) for t in inputs ) ((__a) , ) : Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __a : List[Any] = model(lowerCamelCase_ , labels=lowerCamelCase_ , head_mask=lowerCamelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __a , __a , __a : int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCamelCase_ ): __a : List[str] = entropy(attn.detach() , lowerCamelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCamelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __a : Optional[Any] = 2 __a : Union[str, Any] = torch.pow(torch.pow(lowerCamelCase_ , lowerCamelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: __a : List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(lowerCamelCase_ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(lowerCamelCase_ ) logger.info('Head ranked by importance scores' ) __a : Optional[Any] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __a : str = torch.arange( head_importance.numel() , device=args.device ) __a : Tuple = head_ranks.view_as(lowerCamelCase_ ) print_ad_tensor(lowerCamelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int ): __a , __a , __a : Optional[int] = compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ ) __a : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , lowerCamelCase_ , original_score * args.masking_threshold ) __a : Tuple = torch.ones_like(lowerCamelCase_ ) __a : int = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __a : Tuple = original_score while current_score >= original_score * args.masking_threshold: __a : Optional[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __a : List[str] = float('Inf' ) __a : List[Any] = head_importance.view(-1 ).sort()[1] if len(lowerCamelCase_ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __a : Any = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __a : int = new_head_mask.view(-1 ) __a : Tuple = 0.0 __a : int = new_head_mask.view_as(lowerCamelCase_ ) __a : Optional[int] = new_head_mask.clone().detach() print_ad_tensor(lowerCamelCase_ ) # Compute metric and head importance again __a , __a , __a : int = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[Any] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowerCamelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(lowerCamelCase_ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ ( lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): __a : List[Any] = datetime.now() __a , __a , __a : List[str] = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ ) __a : List[str] = 1 / loss __a : List[Any] = datetime.now() - before_time __a : List[str] = sum(p.numel() for p in model.parameters() ) __a : Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __a : Tuple = [ v, ] assert sum(len(lowerCamelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCamelCase_ ) __a : Optional[Any] = sum(p.numel() for p in model.parameters() ) __a : Tuple = datetime.now() __a , __a , __a : Tuple = compute_heads_importance( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , compute_entropy=lowerCamelCase_ , compute_importance=lowerCamelCase_ , head_mask=lowerCamelCase_ , actually_pruned=lowerCamelCase_ , ) __a : Optional[Any] = 1 / loss __a : List[Any] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowerCamelCase_ , lowerCamelCase_ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , lowerCamelCase_ , lowerCamelCase_ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(lowerCamelCase_ , args.output_dir ) def UpperCAmelCase__ ( ): __a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=lowerCamelCase_ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=lowerCamelCase_ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=lowerCamelCase_ , type=lowerCamelCase_ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=lowerCamelCase_ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=lowerCamelCase_ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=lowerCamelCase_ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=lowerCamelCase_ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=lowerCamelCase_ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=lowerCamelCase_ , help='Batch size.' ) parser.add_argument('--seed' , type=lowerCamelCase_ , default=4_2 ) parser.add_argument('--local_rank' , type=lowerCamelCase_ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=lowerCamelCase_ , default='' , help='Can be used for distant debugging.' ) __a : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCamelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __a : List[str] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __a : Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __a : Union[str, Any] = torch.device('cuda' , args.local_rank ) __a : Any = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __a : Optional[Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __a : List[Any] = nn.parallel.DistributedDataParallel( lowerCamelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCamelCase_ ) elif args.n_gpu > 1: __a : Union[str, Any] = nn.DataParallel(lowerCamelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCamelCase_ ) torch.save(lowerCamelCase_ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , lowerCamelCase_ ) # Prepare dataset __a : Tuple = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __a : str = (torch.from_numpy(lowerCamelCase_ ),) __a : List[str] = TensorDataset(*lowerCamelCase_ ) __a : Optional[Any] = RandomSampler(lowerCamelCase_ ) __a : Union[str, Any] = DataLoader(lowerCamelCase_ , sampler=lowerCamelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __a : Union[str, Any] = mask_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) prune_heads(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
47
0
"""simple docstring""" import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='''%(message)s''') def snake_case ( A__ ): return input_array.reshape((input_array.size, 1) ) def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Optional[int] = np.nan for i in range(A__ ): UpperCAmelCase_ : List[Any] = features[:, labels == i] UpperCAmelCase_ : List[Any] = data.mean(1 ) # Centralize the data of class i UpperCAmelCase_ : List[str] = data - column_reshape(A__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(A__ ,centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase_ : Tuple = np.dot(A__ ,centered_data.T ) return covariance_sum / features.shape[1] def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Optional[int] = features.mean(1 ) UpperCAmelCase_ : Any = np.nan for i in range(A__ ): UpperCAmelCase_ : Optional[Any] = features[:, labels == i] UpperCAmelCase_ : List[Any] = data.shape[1] UpperCAmelCase_ : int = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(A__ ) - column_reshape(A__ ) ,(column_reshape(A__ ) - column_reshape(A__ )).T ,) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase_ : int = device_data * np.dot( column_reshape(A__ ) - column_reshape(A__ ) ,(column_reshape(A__ ) - column_reshape(A__ )).T ,) return covariance_sum / features.shape[1] def snake_case ( A__ ,A__ ): # Check if the features have been loaded if features.any(): UpperCAmelCase_ : Optional[Any] = features.mean(1 ) # Center the dataset UpperCAmelCase_ : Optional[Any] = features - np.reshape(A__ ,(data_mean.size, 1) ) UpperCAmelCase_ : Union[str, Any] = np.dot(A__ ,centered_data.T ) / features.shape[1] UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = np.linalg.eigh(A__ ) # Take all the columns in the reverse order (-1), and then takes only the first UpperCAmelCase_ : List[str] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space UpperCAmelCase_ : List[Any] = np.dot(filtered_eigenvectors.T ,A__ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR ,format="%(message)s" ,force=A__ ) logging.error("Dataset empty" ) raise AssertionError def snake_case ( A__ ,A__ ,A__ ,A__ ): assert classes > dimensions # Check if features have been already loaded if features.any: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = eigh( covariance_between_classes(A__ ,A__ ,A__ ) ,covariance_within_classes(A__ ,A__ ,A__ ) ,) UpperCAmelCase_ : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = np.linalg.svd(A__ ) UpperCAmelCase_ : Optional[int] = svd_matrix[:, 0:dimensions] UpperCAmelCase_ : int = np.dot(filtered_svd_matrix.T ,A__ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR ,format="%(message)s" ,force=A__ ) logging.error("Dataset empty" ) raise AssertionError def snake_case ( ): # Create dummy dataset with 2 classes and 3 features UpperCAmelCase_ : Optional[Any] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) UpperCAmelCase_ : str = np.array([0, 0, 0, 1, 1] ) UpperCAmelCase_ : Dict = 2 UpperCAmelCase_ : List[str] = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(A__ ) as error_info: UpperCAmelCase_ : Tuple = linear_discriminant_analysis( A__ ,A__ ,A__ ,A__ ) if isinstance(A__ ,np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def snake_case ( ): UpperCAmelCase_ : Tuple = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) UpperCAmelCase_ : str = 2 UpperCAmelCase_ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(A__ ) as error_info: UpperCAmelCase_ : Dict = principal_component_analysis(A__ ,A__ ) if not np.allclose(A__ ,A__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
95
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ ( lowerCamelCase_ : str , lowerCamelCase_ : str ): __a : List[Any] = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1_0_2_4, 'hidden_size': 7_6_8, 'max_length': 5_1_2, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1_0_2_4, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __a : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __a : List[str] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __a : int = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __a : Optional[Any] = os.path.join(get_home_dir() , 'models' ) __a : Optional[Any] = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __a : Any = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __a : Dict = original_bort._collect_params_with_prefix() # Build our config 🤗 __a : Optional[Any] = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(lowerCamelCase_ ), } __a : str = BertConfig.from_dict(lowerCamelCase_ ) __a : Optional[int] = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Optional[Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str] ): __a : Optional[int] = hf_param.shape __a : int = to_torch(params[gluon_param] ) __a : int = gluon_param.shape assert ( shape_hf == shape_gluon ), f'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __a : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __a : str = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __a : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __a : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __a : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __a : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __a : BertSelfAttention = layer.attention.self __a : Optional[int] = check_and_map_params( self_attn.key.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __a : str = check_and_map_params( self_attn.key.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __a : List[str] = check_and_map_params( self_attn.query.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __a : str = check_and_map_params( self_attn.query.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __a : Dict = check_and_map_params( self_attn.value.bias.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __a : str = check_and_map_params( self_attn.value.weight.data , f'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __a : BertSelfOutput = layer.attention.output __a : Tuple = check_and_map_params( self_output.dense.bias , f'''encoder.transformer_cells.{i}.proj.bias''' ) __a : Dict = check_and_map_params( self_output.dense.weight , f'''encoder.transformer_cells.{i}.proj.weight''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __a : Optional[Any] = check_and_map_params( self_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __a : BertIntermediate = layer.intermediate __a : List[str] = check_and_map_params( intermediate.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __a : Optional[Any] = check_and_map_params( intermediate.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __a : BertOutput = layer.output __a : str = check_and_map_params( bert_output.dense.bias , f'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __a : List[Any] = check_and_map_params( bert_output.dense.weight , f'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __a : str = check_and_map_params( bert_output.LayerNorm.bias , f'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __a : List[str] = check_and_map_params( bert_output.LayerNorm.weight , f'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __a : Union[str, Any] = RobertaTokenizer.from_pretrained('roberta-base' ) __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ )['input_ids'] # Get gluon output __a : Optional[int] = mx.nd.array([input_ids] ) __a : Tuple = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __a : Optional[Any] = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __a : Union[str, Any] = tokenizer.encode_plus(lowerCamelCase_ , return_tensors='pt' ) __a : int = hf_bort_model(**lowerCamelCase_ )[0] __a : Dict = output_gluon[0].asnumpy() __a : str = output_hf[0].detach().numpy() __a : List[Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __a : str = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
47
0
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __A ( SCREAMING_SNAKE_CASE_ ): UpperCAmelCase__ = "ClapFeatureExtractor" UpperCAmelCase__ = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self : Any , __snake_case : Any , __snake_case : List[Any] ) -> str: super().__init__(__snake_case , __snake_case ) def __call__( self : List[Any] , __snake_case : Optional[int]=None , __snake_case : List[Any]=None , __snake_case : Union[str, Any]=None , **__snake_case : int ) -> Tuple: __magic_name__: Any = kwargs.pop("""sampling_rate""" , __snake_case ) if text is None and audios is None: raise ValueError("""You have to specify either text or audios. Both cannot be none.""" ) if text is not None: __magic_name__: Tuple = self.tokenizer(__snake_case , return_tensors=__snake_case , **__snake_case ) if audios is not None: __magic_name__: Dict = self.feature_extractor( __snake_case , sampling_rate=__snake_case , return_tensors=__snake_case , **__snake_case ) if text is not None and audios is not None: __magic_name__: List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__snake_case ) , tensor_type=__snake_case ) def lowerCamelCase__ ( self : Tuple , *__snake_case : Union[str, Any] , **__snake_case : List[str] ) -> List[str]: return self.tokenizer.batch_decode(*__snake_case , **__snake_case ) def lowerCamelCase__ ( self : Optional[Any] , *__snake_case : int , **__snake_case : str ) -> Any: return self.tokenizer.decode(*__snake_case , **__snake_case ) @property def lowerCamelCase__ ( self : Dict ) -> Tuple: __magic_name__: Any = self.tokenizer.model_input_names __magic_name__: str = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
96
def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ): __a : Any = '' for i in table: res += inp[i - 1] return res def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] ): return data[1:] + data[0] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ): __a : Optional[int] = '' for i in range(len(lowerCamelCase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): __a : List[str] = int('0b' + data[0] + data[-1] , 2 ) __a : List[str] = int('0b' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = message[:4] __a : str = message[4:] __a : Any = apply_table(lowerCamelCase_ , lowerCamelCase_ ) __a : int = xor(lowerCamelCase_ , lowerCamelCase_ ) __a : Dict = apply_sbox(lowerCamelCase_ , temp[:4] ) # noqa: E741 __a : Tuple = apply_sbox(lowerCamelCase_ , temp[4:] ) __a : List[Any] = '0' * (2 - len(lowerCamelCase_ )) + l # noqa: E741 __a : List[str] = '0' * (2 - len(lowerCamelCase_ )) + r __a : List[Any] = apply_table(l + r , lowerCamelCase_ ) __a : Dict = xor(lowerCamelCase_ , lowerCamelCase_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE__ = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE__ = [6, 3, 7, 4, 8, 5, 10, 9] SCREAMING_SNAKE_CASE__ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] SCREAMING_SNAKE_CASE__ = [2, 4, 3, 1] SCREAMING_SNAKE_CASE__ = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE__ = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE__ = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE__ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE__ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE__ = apply_table(key, paa_table) SCREAMING_SNAKE_CASE__ = temp[:5] SCREAMING_SNAKE_CASE__ = temp[5:] SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = left_shift(left) SCREAMING_SNAKE_CASE__ = left_shift(right) SCREAMING_SNAKE_CASE__ = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE__ = apply_table(message, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE__ = apply_table(CT, IP) SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE__ = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE__ = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
47
0
import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowercase__( UpperCAmelCase , unittest.TestCase ): """simple docstring""" a :Tuple = XLMTokenizer a :Any = False def _lowercase ( self : List[Any] ) -> List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] lowercase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowercase_ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[Any]: lowercase_ = '''lower newer''' lowercase_ = '''lower newer''' return input_text, output_text def _lowercase ( self : Union[str, Any] ) -> Any: lowercase_ = XLMTokenizer(self.vocab_file , self.merges_file ) lowercase_ = '''lower''' lowercase_ = ['''low''', '''er</w>'''] lowercase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = tokens + ['''<unk>'''] lowercase_ = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase ( self : int ) -> List[str]: lowercase_ = XLMTokenizer.from_pretrained('''xlm-mlm-en-2048''' ) lowercase_ = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
97
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ : Tuple = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[int] = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Union[str, Any] = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[str] = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
98
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''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 _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''roberta''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : str=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = vocab_size __a : Tuple = hidden_size __a : List[str] = num_hidden_layers __a : List[Any] = num_attention_heads __a : str = hidden_act __a : Optional[Any] = intermediate_size __a : Dict = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Dict = type_vocab_size __a : str = initializer_range __a : List[str] = layer_norm_eps __a : Optional[int] = position_embedding_type __a : Union[str, Any] = use_cache __a : str = classifier_dropout class _UpperCamelCase( __lowerCamelCase ): @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' if self.task == "multiple-choice": __a : List[str] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE = { 'configuration_chinese_clip': [ 'CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ChineseCLIPConfig', 'ChineseCLIPOnnxConfig', 'ChineseCLIPTextConfig', 'ChineseCLIPVisionConfig', ], 'processing_chinese_clip': ['ChineseCLIPProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = ['ChineseCLIPFeatureExtractor'] SCREAMING_SNAKE_CASE = ['ChineseCLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE = [ 'CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ChineseCLIPModel', 'ChineseCLIPPreTrainedModel', 'ChineseCLIPTextModel', 'ChineseCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
99
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = '''▁''' SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} SCREAMING_SNAKE_CASE__ = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } SCREAMING_SNAKE_CASE__ = { '''facebook/xglm-564M''': 2048, } class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="<unk>" , SCREAMING_SNAKE_CASE__ : Dict="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer __a : Any = 7 __a : Union[str, Any] = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words )] __a : Union[str, Any] = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) __a : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Any = 1 # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __a : List[str] = len(self.sp_model ) __a : Optional[int] = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) __a : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[str] ): '''simple docstring''' __a : Tuple = self.__dict__.copy() __a : List[str] = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : int = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Dict = {} __a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a __a : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: __a : List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
47
0
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function _A : List[str] = 1.0_5457_1817E-34 # unit of ℏ : J * s _A : str = 3E8 # unit of c : m * s^-1 def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> dict[str, float]: if (force, area, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if force < 0: raise ValueError('''Magnitude of force can not be negative''' ) if distance < 0: raise ValueError('''Distance can not be negative''' ) if area < 0: raise ValueError('''Area can not be negative''' ) if force == 0: SCREAMING_SNAKE_CASE__ = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_4_0 * (distance) ** 4 ) return {"force": force} elif area == 0: SCREAMING_SNAKE_CASE__ = (2_4_0 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: SCREAMING_SNAKE_CASE__ = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_4_0 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('''One and only one argument must be 0''' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
100
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] SCREAMING_SNAKE_CASE__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def UpperCAmelCase__ ( lowerCamelCase_ : Optional[int] ): __a : str = torch.load(lowerCamelCase_ , map_location='cpu' ) return sd def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict=rename_keys_prefix ): __a : Optional[Any] = OrderedDict() __a : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a : List[Any] = key for name_pair in rename_keys_prefix: __a : List[str] = new_key.replace(name_pair[0] , name_pair[1] ) __a : Any = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a : int = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def UpperCAmelCase__ ( lowerCamelCase_ : Any , lowerCamelCase_ : Any ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a : Dict = 'pretraining' if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __a : int = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __a : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a : int = {'visual_embedding_dim': 5_1_2} __a : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __a : Any = {'visual_embedding_dim': 2_0_4_8} __a : List[str] = 'vqa_advanced' elif "vqa" in checkpoint_path: __a : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __a : List[Any] = 'vqa' elif "nlvr" in checkpoint_path: __a : Optional[int] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __a : Optional[Any] = 'nlvr' __a : str = VisualBertConfig(**lowerCamelCase_ ) # Load State Dict __a : str = load_state_dict(lowerCamelCase_ ) __a : str = get_new_dict(lowerCamelCase_ , lowerCamelCase_ ) if model_type == "pretraining": __a : Optional[Any] = VisualBertForPreTraining(lowerCamelCase_ ) elif model_type == "vqa": __a : Any = VisualBertForQuestionAnswering(lowerCamelCase_ ) elif model_type == "nlvr": __a : int = VisualBertForVisualReasoning(lowerCamelCase_ ) elif model_type == "multichoice": __a : Optional[int] = VisualBertForMultipleChoice(lowerCamelCase_ ) model.load_state_dict(lowerCamelCase_ ) # Save Checkpoints Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
47
0