code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
def lowerCAmelCase ( lowerCAmelCase_ = 100 )-> int: lowerCAmelCase_ : Any = n * (n + 1) * (2 * n + 1) / 6 lowerCAmelCase_ : Any = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
262
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Optional[Any] =logging.get_logger(__name__) _UpperCAmelCase : str ={ """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class snake_case__( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = """vit_mae""" def __init__( self , __lowercase=7_6_8 , __lowercase=1_2 , __lowercase=1_2 , __lowercase=3_0_7_2 , __lowercase="gelu" , __lowercase=0.0 , __lowercase=0.0 , __lowercase=0.02 , __lowercase=1e-12 , __lowercase=2_2_4 , __lowercase=1_6 , __lowercase=3 , __lowercase=True , __lowercase=1_6 , __lowercase=5_1_2 , __lowercase=8 , __lowercase=2_0_4_8 , __lowercase=0.75 , __lowercase=False , **__lowercase , ) -> str: super().__init__(**__lowercase ) lowerCAmelCase_ : Dict = hidden_size lowerCAmelCase_ : Any = num_hidden_layers lowerCAmelCase_ : Any = num_attention_heads lowerCAmelCase_ : int = intermediate_size lowerCAmelCase_ : Dict = hidden_act lowerCAmelCase_ : int = hidden_dropout_prob lowerCAmelCase_ : str = attention_probs_dropout_prob lowerCAmelCase_ : List[str] = initializer_range lowerCAmelCase_ : Dict = layer_norm_eps lowerCAmelCase_ : Union[str, Any] = image_size lowerCAmelCase_ : Optional[int] = patch_size lowerCAmelCase_ : Tuple = num_channels lowerCAmelCase_ : List[str] = qkv_bias lowerCAmelCase_ : List[Any] = decoder_num_attention_heads lowerCAmelCase_ : int = decoder_hidden_size lowerCAmelCase_ : Optional[int] = decoder_num_hidden_layers lowerCAmelCase_ : Tuple = decoder_intermediate_size lowerCAmelCase_ : Tuple = mask_ratio lowerCAmelCase_ : Any = norm_pix_loss
262
1
from __future__ import annotations import math def __lowercase ( a__ , a__ ) -> float: __SCREAMING_SNAKE_CASE = u for i in range(1 , a__ ): __SCREAMING_SNAKE_CASE = temp * (u - i) return temp def __lowercase ( ) -> None: __SCREAMING_SNAKE_CASE = int(input('enter the numbers of values: ' ) ) __SCREAMING_SNAKE_CASE = [] for _ in range(a__ ): y.append([] ) for i in range(a__ ): for j in range(a__ ): y[i].append(a__ ) __SCREAMING_SNAKE_CASE = 0 print('enter the values of parameters in a list: ' ) __SCREAMING_SNAKE_CASE = list(map(a__ , input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(a__ ): __SCREAMING_SNAKE_CASE = float(input() ) __SCREAMING_SNAKE_CASE = int(input('enter the value to interpolate: ' ) ) __SCREAMING_SNAKE_CASE = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , a__ ): for j in range(n - i ): __SCREAMING_SNAKE_CASE = y[j + 1][i - 1] - y[j][i - 1] __SCREAMING_SNAKE_CASE = y[0][0] for i in range(1 , a__ ): summ += (ucal(a__ , a__ ) * y[0][i]) / math.factorial(a__ ) print(f"""the value at {value} is {summ}""" ) if __name__ == "__main__": main()
363
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Union[str, Any] = '''Wav2Vec2FeatureExtractor''' UpperCamelCase__ : Union[str, Any] = '''AutoTokenizer''' def __init__( self , _A , _A ): '''simple docstring''' super().__init__(_A , _A ) __SCREAMING_SNAKE_CASE = self.feature_extractor __SCREAMING_SNAKE_CASE = False @classmethod def _A ( cls , _A , **_A ): '''simple docstring''' try: return super().from_pretrained(_A , **_A ) except OSError: warnings.warn( f"""Loading a tokenizer inside {cls.__name__} from a config that does not""" ' include a `tokenizer_class` attribute is deprecated and will be ' 'removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`' ' attribute to either your `config.json` or `tokenizer_config.json` ' 'file to suppress this warning: ' , _A , ) __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer.from_pretrained(_A , **_A ) return cls(feature_extractor=_A , tokenizer=_A ) def __call__( self , *_A , **_A ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*_A , **_A ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) __SCREAMING_SNAKE_CASE = kwargs.pop('raw_speech' ) else: __SCREAMING_SNAKE_CASE = kwargs.pop('audio' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('sampling_rate' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('text' , _A ) if len(_A ) > 0: __SCREAMING_SNAKE_CASE = args[0] __SCREAMING_SNAKE_CASE = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: __SCREAMING_SNAKE_CASE = self.feature_extractor(_A , *_A , sampling_rate=_A , **_A ) if text is not None: __SCREAMING_SNAKE_CASE = self.tokenizer(_A , **_A ) if text is None: return inputs elif audio is None: return encodings else: __SCREAMING_SNAKE_CASE = encodings['input_ids'] return inputs def _A ( self , *_A , **_A ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor.pad(*_A , **_A ) __SCREAMING_SNAKE_CASE = kwargs.pop('input_features' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('labels' , _A ) if len(_A ) > 0: __SCREAMING_SNAKE_CASE = args[0] __SCREAMING_SNAKE_CASE = args[1:] if input_features is not None: __SCREAMING_SNAKE_CASE = self.feature_extractor.pad(_A , *_A , **_A ) if labels is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.pad(_A , **_A ) if labels is None: return input_features elif input_features is None: return labels else: __SCREAMING_SNAKE_CASE = labels['input_ids'] return input_features def _A ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.batch_decode(*_A , **_A ) def _A ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.decode(*_A , **_A ) @contextmanager def _A ( self ): '''simple docstring''' warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer yield __SCREAMING_SNAKE_CASE = self.feature_extractor __SCREAMING_SNAKE_CASE = False
118
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ={'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE_: int ={ 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE_: str ={ 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) SCREAMING_SNAKE_CASE_: Dict =0 SCREAMING_SNAKE_CASE_: Tuple =1 SCREAMING_SNAKE_CASE_: Optional[int] =2 SCREAMING_SNAKE_CASE_: List[str] =3 SCREAMING_SNAKE_CASE_: Optional[int] =4 class __A ( lowerCAmelCase__ ): a__ : Dict = VOCAB_FILES_NAMES a__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[str] = """left""" def __init__(self : Tuple , __a : int , __a : Any=False , __a : Tuple=True , __a : Optional[Any]=False , __a : Dict="<s>" , __a : Dict="</s>" , __a : int="<unk>" , __a : Tuple="<sep>" , __a : Any="<pad>" , __a : Optional[Any]="<cls>" , __a : Any="<mask>" , __a : Optional[int]=["<eop>", "<eod>"] , __a : int = None , **__a : List[str] , ): # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token UpperCAmelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase__ , remove_space=UpperCamelCase__ , keep_accents=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) UpperCAmelCase_ = 3 UpperCAmelCase_ = do_lower_case UpperCAmelCase_ = remove_space UpperCAmelCase_ = keep_accents UpperCAmelCase_ = vocab_file UpperCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @property def _lowercase (self : List[Any] ): return len(self.sp_model ) def _lowercase (self : Dict ): UpperCAmelCase_ = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self : Dict ): UpperCAmelCase_ = self.__dict__.copy() UpperCAmelCase_ = None return state def __setstate__(self : Union[str, Any] , __a : int ): UpperCAmelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase_ = {} UpperCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase (self : Any , __a : List[Any] ): if self.remove_space: UpperCAmelCase_ = " ".join(inputs.strip().split() ) else: UpperCAmelCase_ = inputs UpperCAmelCase_ = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: UpperCAmelCase_ = unicodedata.normalize("NFKD" , UpperCamelCase__ ) UpperCAmelCase_ = "".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__ )] ) if self.do_lower_case: UpperCAmelCase_ = outputs.lower() return outputs def _lowercase (self : Optional[Any] , __a : Any ): UpperCAmelCase_ = self.preprocess_text(UpperCamelCase__ ) UpperCAmelCase_ = self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) UpperCAmelCase_ = [] for piece in pieces: if len(UpperCamelCase__ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): UpperCAmelCase_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: UpperCAmelCase_ = cur_pieces[1:] else: UpperCAmelCase_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase__ ) else: new_pieces.append(UpperCamelCase__ ) return new_pieces def _lowercase (self : List[Any] , __a : Union[str, Any] ): return self.sp_model.PieceToId(UpperCamelCase__ ) def _lowercase (self : List[str] , __a : Any ): return self.sp_model.IdToPiece(UpperCamelCase__ ) def _lowercase (self : Any , __a : int ): UpperCAmelCase_ = "".join(UpperCamelCase__ ).replace(UpperCamelCase__ , " " ).strip() return out_string def _lowercase (self : str , __a : Union[str, Any] , __a : str = False , __a : Dict = None , __a : str = True , **__a : List[Any] , ): UpperCAmelCase_ = kwargs.pop("use_source_tokenizer" , UpperCamelCase__ ) UpperCAmelCase_ = self.convert_ids_to_tokens(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCAmelCase_ = [] UpperCAmelCase_ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) UpperCAmelCase_ = [] sub_texts.append(UpperCamelCase__ ) else: current_sub_text.append(UpperCamelCase__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens UpperCAmelCase_ = "".join(UpperCamelCase__ ) UpperCAmelCase_ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCAmelCase_ = self.clean_up_tokenization(UpperCamelCase__ ) return clean_text else: return text def _lowercase (self : Any , __a : str , __a : Tuple = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase (self : int , __a : List[str] , __a : List[str] = None , __a : Tuple = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is not None: return ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] return ([0] * len(UpperCamelCase__ )) + [1, 1] def _lowercase (self : int , __a : int , __a : Union[str, Any] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _lowercase (self : Optional[Any] , __a : str , __a : List[Any] = None ): if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ = os.path.join( UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , "wb" ) as fi: UpperCAmelCase_ = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE__ : int = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE__ : str = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : Optional[int] = 2 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = 4 class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Dict = VOCAB_FILES_NAMES lowerCamelCase_ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ : List[str] = """left""" def __init__( self , UpperCamelCase__ , UpperCamelCase__=False , UpperCamelCase__=True , UpperCamelCase__=False , UpperCamelCase__="<s>" , UpperCamelCase__="</s>" , UpperCamelCase__="<unk>" , UpperCamelCase__="<sep>" , UpperCamelCase__="<pad>" , UpperCamelCase__="<cls>" , UpperCamelCase__="<mask>" , UpperCamelCase__=["<eop>", "<eod>"] , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase : str = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token lowerCamelCase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase__ , remove_space=UpperCamelCase__ , keep_accents=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) lowerCamelCase : Any = 3 lowerCamelCase : Optional[Any] = do_lower_case lowerCamelCase : List[Any] = remove_space lowerCamelCase : str = keep_accents lowerCamelCase : List[Any] = vocab_file lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @property def _lowercase ( self ) -> Optional[Any]: return len(self.sp_model ) def _lowercase ( self ) -> Optional[int]: lowerCamelCase : int = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[Any]: lowerCamelCase : Optional[int] = self.__dict__.copy() lowerCamelCase : Union[str, Any] = None return state def __setstate__( self , UpperCamelCase__ ) -> int: lowerCamelCase : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase : Any = {} lowerCamelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self , UpperCamelCase__ ) -> Any: if self.remove_space: lowerCamelCase : Dict = " ".join(inputs.strip().split() ) else: lowerCamelCase : Union[str, Any] = inputs lowerCamelCase : Optional[Any] = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase : Optional[int] = unicodedata.normalize("NFKD" , UpperCamelCase__ ) lowerCamelCase : List[Any] = "".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__ )] ) if self.do_lower_case: lowerCamelCase : List[str] = outputs.lower() return outputs def _lowercase ( self , UpperCamelCase__ ) -> List[str]: lowerCamelCase : Optional[Any] = self.preprocess_text(UpperCamelCase__ ) lowerCamelCase : Dict = self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) lowerCamelCase : Dict = [] for piece in pieces: if len(UpperCamelCase__ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase : List[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: lowerCamelCase : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase__ ) else: new_pieces.append(UpperCamelCase__ ) return new_pieces def _lowercase ( self , UpperCamelCase__ ) -> int: return self.sp_model.PieceToId(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> Tuple: return self.sp_model.IdToPiece(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> List[str]: lowerCamelCase : Union[str, Any] = "".join(UpperCamelCase__ ).replace(UpperCamelCase__ , " " ).strip() return out_string def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , UpperCamelCase__ = True , **UpperCamelCase__ , ) -> str: lowerCamelCase : Optional[int] = kwargs.pop("use_source_tokenizer" , UpperCamelCase__ ) lowerCamelCase : Optional[int] = self.convert_ids_to_tokens(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCamelCase : Any = [] lowerCamelCase : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) lowerCamelCase : int = [] sub_texts.append(UpperCamelCase__ ) else: current_sub_text.append(UpperCamelCase__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase : Union[str, Any] = "".join(UpperCamelCase__ ) lowerCamelCase : Tuple = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase : int = self.clean_up_tokenization(UpperCamelCase__ ) return clean_text else: return text def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> List[int]: lowerCamelCase : str = [self.sep_token_id] lowerCamelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is not None: return ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] return ([0] * len(UpperCamelCase__ )) + [1, 1] def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> List[int]: lowerCamelCase : Any = [self.sep_token_id] lowerCamelCase : List[str] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase : Union[str, Any] = os.path.join( UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , "wb" ) as fi: lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
48
0
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( snake_case )-> Optional[Any]: '''simple docstring''' if length <= 0 or not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise ValueError("Length must be a positive integer." ) return [n * (2 * n - 1) for n in range(lowerCamelCase__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
350
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def SCREAMING_SNAKE_CASE__ ( snake_case : Dataset , snake_case : Dict[str, str] )-> Any: '''simple docstring''' UpperCAmelCase__ : str = args.log_outputs UpperCAmelCase__ : str = "_".join(args.dataset.split("/" ) + [args.config, args.split] ) # load metric UpperCAmelCase__ : List[str] = load_metric("wer" ) UpperCAmelCase__ : Tuple = load_metric("cer" ) # compute metrics UpperCAmelCase__ : List[str] = wer.compute(references=result["target"] , predictions=result["prediction"] ) UpperCAmelCase__ : Tuple = cer.compute(references=result["target"] , predictions=result["prediction"] ) # print & log results UpperCAmelCase__ : Union[str, Any] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case ) with open(f'{dataset_id}_eval_results.txt' , "w" ) as f: f.write(snake_case ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCAmelCase__ : str = f'log_{dataset_id}_predictions.txt' UpperCAmelCase__ : List[str] = f'log_{dataset_id}_targets.txt' with open(snake_case , "w" ) as p, open(snake_case , "w" ) as t: # mapping function to write output def write_to_file(snake_case : List[Any] , snake_case : List[str] ): p.write(f'{i}' + "\n" ) p.write(batch["prediction"] + "\n" ) t.write(f'{i}' + "\n" ) t.write(batch["target"] + "\n" ) result.map(snake_case , with_indices=snake_case ) def SCREAMING_SNAKE_CASE__ ( snake_case : str )-> str: '''simple docstring''' UpperCAmelCase__ : str = "[,?.!\-\;\:\"“%‘”�—’…–]" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCAmelCase__ : str = re.sub(snake_case , "" , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCAmelCase__ : Tuple = ["\n\n", "\n", " ", " "] for t in token_sequences_to_ignore: UpperCAmelCase__ : List[Any] = " ".join(text.split(snake_case ) ) return text def SCREAMING_SNAKE_CASE__ ( snake_case : List[str] )-> str: '''simple docstring''' UpperCAmelCase__ : Optional[int] = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=snake_case ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCAmelCase__ : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCAmelCase__ : str = feature_extractor.sampling_rate # resample audio UpperCAmelCase__ : Dict = dataset.cast_column("audio" , Audio(sampling_rate=snake_case ) ) # load eval pipeline if args.device is None: UpperCAmelCase__ : List[str] = 0 if torch.cuda.is_available() else -1 UpperCAmelCase__ : Optional[int] = pipeline("automatic-speech-recognition" , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(snake_case : Any ): UpperCAmelCase__ : List[str] = asr( batch["audio"]["array"] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) UpperCAmelCase__ : List[Any] = prediction["text"] UpperCAmelCase__ : Optional[int] = normalize_text(batch["sentence"] ) return batch # run inference on all examples UpperCAmelCase__ : Dict = dataset.map(snake_case , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case , snake_case ) if __name__ == "__main__": _lowerCAmelCase : Any = argparse.ArgumentParser() parser.add_argument( """--model_id""", type=str, required=True, help="""Model identifier. Should be loadable with 🤗 Transformers""" ) parser.add_argument( """--dataset""", type=str, required=True, help="""Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets""", ) parser.add_argument( """--config""", type=str, required=True, help="""Config of the dataset. *E.g.* `'en'` for Common Voice""" ) parser.add_argument("""--split""", type=str, required=True, help="""Split of the dataset. *E.g.* `'test'`""") parser.add_argument( """--chunk_length_s""", type=float, default=None, help="""Chunk length in seconds. Defaults to 5 seconds.""" ) parser.add_argument( """--stride_length_s""", type=float, default=None, help="""Stride of the audio chunks. Defaults to 1 second.""" ) parser.add_argument( """--log_outputs""", action="""store_true""", help="""If defined, write outputs to log file for analysis.""" ) parser.add_argument( """--device""", type=int, default=None, help="""The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.""", ) _lowerCAmelCase : Tuple = parser.parse_args() main(args)
298
0
'''simple docstring''' def __snake_case( _lowerCAmelCase ) -> int: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: snake_case__ : Optional[Any] = f"The input value of [n={number}] has to be > 0" raise ValueError(_lowerCAmelCase ) else: snake_case__ : Optional[Any] = sylvester(number - 1 ) snake_case__ : Union[str, Any] = num - 1 snake_case__ : List[str] = num return lower * upper + 1 if __name__ == "__main__": print(F"The 8th number in Sylvester\'s sequence: {sylvester(8)}")
35
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() _A : List[Any] =logging.get_logger(__name__) _A : Dict =['''model.decoder.embed_positions.weights'''] def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: if "emb" in name: lowerCamelCase__ : Dict = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: lowerCamelCase__ : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: lowerCamelCase__ : List[str] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: lowerCamelCase__ : Optional[int] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: lowerCamelCase__ : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: lowerCamelCase__ : Dict = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: lowerCamelCase__ : Optional[Any] = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: lowerCamelCase__ : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: lowerCamelCase__ : Optional[Any] = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: lowerCamelCase__ : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: lowerCamelCase__ : int = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Tuple[Dict, Dict]: lowerCamelCase__ : int = list(state_dict.keys() ) lowerCamelCase__ : Tuple = {} for key in keys: lowerCamelCase__ : Any = state_dict.pop(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = rename_keys(UpperCamelCase ) if "in_proj_weight" in key: # split fused qkv proj lowerCamelCase__ : Union[str, Any] = val[:hidden_size, :] lowerCamelCase__ : Any = val[hidden_size : 2 * hidden_size, :] lowerCamelCase__ : Optional[int] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: lowerCamelCase__ : str = val else: lowerCamelCase__ : Union[str, Any] = val return state_dict, enc_dec_proj_state_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values lowerCamelCase__ : int = 1024 lowerCamelCase__ : int = 24 lowerCamelCase__ : List[Any] = 16 elif checkpoint == "medium": lowerCamelCase__ : Any = 1536 lowerCamelCase__ : Union[str, Any] = 48 lowerCamelCase__ : Optional[int] = 24 elif checkpoint == "large": lowerCamelCase__ : Optional[Any] = 2048 lowerCamelCase__ : Dict = 48 lowerCamelCase__ : List[Any] = 32 else: raise ValueError(f'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) lowerCamelCase__ : Any = MusicgenDecoderConfig( hidden_size=UpperCamelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=UpperCamelCase , num_attention_heads=UpperCamelCase , ) return config @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase="cpu" ) -> Optional[Any]: lowerCamelCase__ : Optional[int] = MusicGen.get_pretrained(UpperCamelCase , device=UpperCamelCase ) lowerCamelCase__ : List[Any] = decoder_config_from_checkpoint(UpperCamelCase ) lowerCamelCase__ : Any = fairseq_model.lm.state_dict() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = rename_state_dict( UpperCamelCase , hidden_size=decoder_config.hidden_size ) lowerCamelCase__ : str = TaEncoderModel.from_pretrained("""t5-base""" ) lowerCamelCase__ : Tuple = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) lowerCamelCase__ : Optional[int] = MusicgenForCausalLM(UpperCamelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection lowerCamelCase__ , lowerCamelCase__ : List[str] = decoder.load_state_dict(UpperCamelCase , strict=UpperCamelCase ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(UpperCamelCase ) if len(UpperCamelCase ) > 0: raise ValueError(f'''Missing key(s) in state_dict: {missing_keys}''' ) if len(UpperCamelCase ) > 0: raise ValueError(f'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model lowerCamelCase__ : Optional[Any] = MusicgenForConditionalGeneration(text_encoder=UpperCamelCase , audio_encoder=UpperCamelCase , decoder=UpperCamelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(UpperCamelCase ) # check we can do a forward pass lowerCamelCase__ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) lowerCamelCase__ : Optional[Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): lowerCamelCase__ : Union[str, Any] = model(input_ids=UpperCamelCase , decoder_input_ids=UpperCamelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor lowerCamelCase__ : str = AutoTokenizer.from_pretrained("""t5-base""" ) lowerCamelCase__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) lowerCamelCase__ : Optional[int] = MusicgenProcessor(feature_extractor=UpperCamelCase , tokenizer=UpperCamelCase ) # set the appropriate bos/pad token ids lowerCamelCase__ : Union[str, Any] = 2048 lowerCamelCase__ : List[str] = 2048 # set other default generation config params lowerCamelCase__ : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[Any] = 3.0 if pytorch_dump_folder is not None: Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) logger.info(f'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) if repo_id: logger.info(f'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(UpperCamelCase ) processor.push_to_hub(UpperCamelCase ) if __name__ == "__main__": _A : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) _A : List[str] =parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
41
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase : Any = logging.get_logger(__name__) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SwinConfig( embed_dim=1_92 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['stage2', 'stage3', 'stage4'] , ) _SCREAMING_SNAKE_CASE =DetaConfig( backbone_config=_UpperCamelCase , num_queries=9_00 , encoder_ffn_dim=20_48 , decoder_ffn_dim=20_48 , num_feature_levels=5 , assign_first_stage=_UpperCamelCase , with_box_refine=_UpperCamelCase , two_stage=_UpperCamelCase , ) # set labels _SCREAMING_SNAKE_CASE ='huggingface/label-files' if "o365" in model_name: _SCREAMING_SNAKE_CASE =3_66 _SCREAMING_SNAKE_CASE ='object365-id2label.json' else: _SCREAMING_SNAKE_CASE =91 _SCREAMING_SNAKE_CASE ='coco-detection-id2label.json' _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) ) , 'r' ) ) _SCREAMING_SNAKE_CASE ={int(_UpperCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE =idalabel _SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} return config def _lowerCAmelCase ( _UpperCamelCase : List[Any] ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =[] # stem # fmt: off rename_keys.append(('backbone.0.body.patch_embed.proj.weight', 'model.backbone.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.0.body.patch_embed.proj.bias', 'model.backbone.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.0.body.patch_embed.norm.weight', 'model.backbone.model.embeddings.norm.weight') ) rename_keys.append(('backbone.0.body.patch_embed.norm.bias', 'model.backbone.model.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((f"backbone.0.body.layers.{i}.downsample.reduction.weight", f"model.backbone.model.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.weight", f"model.backbone.model.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.bias", f"model.backbone.model.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append(('backbone.0.body.norm1.weight', 'model.backbone.model.hidden_states_norms.stage2.weight') ) rename_keys.append(('backbone.0.body.norm1.bias', 'model.backbone.model.hidden_states_norms.stage2.bias') ) rename_keys.append(('backbone.0.body.norm2.weight', 'model.backbone.model.hidden_states_norms.stage3.weight') ) rename_keys.append(('backbone.0.body.norm2.bias', 'model.backbone.model.hidden_states_norms.stage3.bias') ) rename_keys.append(('backbone.0.body.norm3.weight', 'model.backbone.model.hidden_states_norms.stage4.weight') ) rename_keys.append(('backbone.0.body.norm3.bias', 'model.backbone.model.hidden_states_norms.stage4.bias') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight", f"model.encoder.layers.{i}.self_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias", f"model.encoder.layers.{i}.self_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.weight", f"model.encoder.layers.{i}.self_attn.attention_weights.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.bias", f"model.encoder.layers.{i}.self_attn.attention_weights.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.weight", f"model.encoder.layers.{i}.self_attn.value_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.bias", f"model.encoder.layers.{i}.self_attn.value_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.weight", f"model.encoder.layers.{i}.self_attn.output_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.bias", f"model.encoder.layers.{i}.self_attn.output_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.weight", f"model.encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"model.encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"model.encoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"model.encoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"model.encoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"model.encoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"model.encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"model.encoder.layers.{i}.final_layer_norm.bias") ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.weight", f"model.decoder.layers.{i}.encoder_attn.attention_weights.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.bias", f"model.decoder.layers.{i}.encoder_attn.attention_weights.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.weight", f"model.decoder.layers.{i}.encoder_attn.value_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.bias", f"model.decoder.layers.{i}.encoder_attn.value_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.weight", f"model.decoder.layers.{i}.encoder_attn.output_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.bias", f"model.decoder.layers.{i}.encoder_attn.output_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.weight", f"model.decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"model.decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"model.decoder.layers.{i}.self_attn.out_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"model.decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.weight", f"model.decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.bias", f"model.decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"model.decoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"model.decoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"model.decoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"model.decoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"model.decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"model.decoder.layers.{i}.final_layer_norm.bias") ) # fmt: on return rename_keys def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Tuple , _UpperCamelCase : List[str] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =dct.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =val def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : str ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =[int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): _SCREAMING_SNAKE_CASE =num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) _SCREAMING_SNAKE_CASE =state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight" ) _SCREAMING_SNAKE_CASE =state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE =in_proj_weight[:dim, :] _SCREAMING_SNAKE_CASE =in_proj_bias[: dim] _SCREAMING_SNAKE_CASE =in_proj_weight[ dim : dim * 2, : ] _SCREAMING_SNAKE_CASE =in_proj_bias[ dim : dim * 2 ] _SCREAMING_SNAKE_CASE =in_proj_weight[ -dim :, : ] _SCREAMING_SNAKE_CASE =in_proj_bias[-dim :] # fmt: on def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : str ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention _SCREAMING_SNAKE_CASE =state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) _SCREAMING_SNAKE_CASE =state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE =in_proj_weight[:hidden_size, :] _SCREAMING_SNAKE_CASE =in_proj_bias[:hidden_size] _SCREAMING_SNAKE_CASE =in_proj_weight[ hidden_size : hidden_size * 2, : ] _SCREAMING_SNAKE_CASE =in_proj_bias[hidden_size : hidden_size * 2] _SCREAMING_SNAKE_CASE =in_proj_weight[-hidden_size:, :] _SCREAMING_SNAKE_CASE =in_proj_bias[-hidden_size:] def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE ='http://images.cocodataset.org/val2017/000000039769.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str] ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =get_deta_config(_UpperCamelCase ) # load original state dict if model_name == "deta-swin-large": _SCREAMING_SNAKE_CASE =hf_hub_download(repo_id='nielsr/deta-checkpoints' , filename='adet_swin_ft.pth' ) elif model_name == "deta-swin-large-o365": _SCREAMING_SNAKE_CASE =hf_hub_download(repo_id='jozhang97/deta-swin-l-o365' , filename='deta_swin_pt_o365.pth' ) else: raise ValueError(f"Model name {model_name} not supported" ) _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' )['model'] # original state dict for name, param in state_dict.items(): print(_UpperCamelCase , param.shape ) # rename keys _SCREAMING_SNAKE_CASE =create_rename_keys(_UpperCamelCase ) for src, dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) read_in_swin_q_k_v(_UpperCamelCase , config.backbone_config ) read_in_decoder_q_k_v(_UpperCamelCase , _UpperCamelCase ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: _SCREAMING_SNAKE_CASE =state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =val if "input_proj" in key: _SCREAMING_SNAKE_CASE =state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: _SCREAMING_SNAKE_CASE =state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =val # finally, create HuggingFace model and load state dict _SCREAMING_SNAKE_CASE =DetaForObjectDetection(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) model.eval() _SCREAMING_SNAKE_CASE ='cuda' if torch.cuda.is_available() else 'cpu' model.to(_UpperCamelCase ) # load image processor _SCREAMING_SNAKE_CASE =DetaImageProcessor(format='coco_detection' ) # verify our conversion on image _SCREAMING_SNAKE_CASE =prepare_img() _SCREAMING_SNAKE_CASE =processor(images=_UpperCamelCase , return_tensors='pt' ) _SCREAMING_SNAKE_CASE =encoding['pixel_values'] _SCREAMING_SNAKE_CASE =model(pixel_values.to(_UpperCamelCase ) ) # verify logits print('Logits:' , outputs.logits[0, :3, :3] ) print('Boxes:' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": _SCREAMING_SNAKE_CASE =torch.tensor( [[-7.63_08, -2.84_85, -5.37_37], [-7.20_37, -4.55_05, -4.80_27], [-7.29_43, -4.26_11, -4.66_17]] ) _SCREAMING_SNAKE_CASE =torch.tensor([[0.49_87, 0.49_69, 0.99_99], [0.25_49, 0.54_98, 0.48_05], [0.54_98, 0.27_57, 0.05_69]] ) elif model_name == "deta-swin-large-o365": _SCREAMING_SNAKE_CASE =torch.tensor( [[-8.01_22, -3.57_20, -4.97_17], [-8.15_47, -3.68_86, -4.63_89], [-7.66_10, -3.61_94, -5.01_34]] ) _SCREAMING_SNAKE_CASE =torch.tensor([[0.25_23, 0.55_49, 0.48_81], [0.77_15, 0.41_49, 0.46_01], [0.55_03, 0.27_53, 0.05_75]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(_UpperCamelCase ) , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(_UpperCamelCase ) , atol=1E-4 ) print('Everything ok!' ) if pytorch_dump_folder_path: # Save model and processor logger.info(f"Saving PyTorch model and processor to {pytorch_dump_folder_path}..." ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) processor.save_pretrained(_UpperCamelCase ) # Push to hub if push_to_hub: print('Pushing model and processor to hub...' ) model.push_to_hub(f"jozhang97/{model_name}" ) processor.push_to_hub(f"jozhang97/{model_name}" ) if __name__ == "__main__": lowerCamelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default="deta-swin-large", choices=["deta-swin-large", "deta-swin-large-o365"], help="Name of the model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowerCamelCase : List[Any] = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
114
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCamelCase : List[str] = random.Random() def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : List[str]=1.0 , _UpperCamelCase : Optional[int]=None , _UpperCamelCase : Dict=None ) -> Any: """simple docstring""" if rng is None: _SCREAMING_SNAKE_CASE =global_rng _SCREAMING_SNAKE_CASE =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A__ ( unittest.TestCase ): def __init__( self : List[Any] , _a : Tuple , _a : Dict=7 , _a : List[Any]=400 , _a : List[str]=2000 , _a : Optional[Any]=10 , _a : Dict=160 , _a : Tuple=8 , _a : Any=0.0 , _a : Optional[Any]=4000 , _a : List[Any]=False , _a : Dict=True , ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =min_seq_length _SCREAMING_SNAKE_CASE =max_seq_length _SCREAMING_SNAKE_CASE =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _SCREAMING_SNAKE_CASE =padding_value _SCREAMING_SNAKE_CASE =sampling_rate _SCREAMING_SNAKE_CASE =return_attention_mask _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =feature_size _SCREAMING_SNAKE_CASE =chunk_length _SCREAMING_SNAKE_CASE =hop_length def A ( self : Any ) -> Optional[Any]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def A ( self : Optional[Any] , _a : Any=False , _a : Union[str, Any]=False ) -> Optional[Any]: '''simple docstring''' def _flatten(_a : Union[str, Any] ): return list(itertools.chain(*_a ) ) if equal_length: _SCREAMING_SNAKE_CASE =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _SCREAMING_SNAKE_CASE =[ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _SCREAMING_SNAKE_CASE =[np.asarray(_a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( A__ , unittest.TestCase ): A__ = WhisperFeatureExtractor if is_speech_available() else None def A ( self : Union[str, Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =WhisperFeatureExtractionTester(self ) def A ( self : str ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _SCREAMING_SNAKE_CASE =feat_extract_first.save_pretrained(_a )[0] check_json_file_has_correct_format(_a ) _SCREAMING_SNAKE_CASE =self.feature_extraction_class.from_pretrained(_a ) _SCREAMING_SNAKE_CASE =feat_extract_first.to_dict() _SCREAMING_SNAKE_CASE =feat_extract_second.to_dict() _SCREAMING_SNAKE_CASE =feat_extract_first.mel_filters _SCREAMING_SNAKE_CASE =feat_extract_second.mel_filters self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def A ( self : Tuple ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _SCREAMING_SNAKE_CASE =os.path.join(_a , 'feat_extract.json' ) feat_extract_first.to_json_file(_a ) _SCREAMING_SNAKE_CASE =self.feature_extraction_class.from_json_file(_a ) _SCREAMING_SNAKE_CASE =feat_extract_first.to_dict() _SCREAMING_SNAKE_CASE =feat_extract_second.to_dict() _SCREAMING_SNAKE_CASE =feat_extract_first.mel_filters _SCREAMING_SNAKE_CASE =feat_extract_second.mel_filters self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def A ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _SCREAMING_SNAKE_CASE =[floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _SCREAMING_SNAKE_CASE =[np.asarray(_a ) for speech_input in speech_inputs] # Test feature size _SCREAMING_SNAKE_CASE =feature_extractor(_a , padding='max_length' , return_tensors='np' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input _SCREAMING_SNAKE_CASE =feature_extractor(speech_inputs[0] , return_tensors='np' ).input_features _SCREAMING_SNAKE_CASE =feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_features self.assertTrue(np.allclose(_a , _a , atol=1e-3 ) ) # Test batched _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(_a , _a ): self.assertTrue(np.allclose(_a , _a , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _SCREAMING_SNAKE_CASE =[floats_list((1, x) )[0] for x in (800, 800, 800)] _SCREAMING_SNAKE_CASE =np.asarray(_a ) _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(_a , _a ): self.assertTrue(np.allclose(_a , _a , atol=1e-3 ) ) # Test truncation required _SCREAMING_SNAKE_CASE =[floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] _SCREAMING_SNAKE_CASE =[np.asarray(_a ) for speech_input in speech_inputs] _SCREAMING_SNAKE_CASE =[x[: feature_extractor.n_samples] for x in speech_inputs] _SCREAMING_SNAKE_CASE =[np.asarray(_a ) for speech_input in speech_inputs_truncated] _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(_a , _a ): self.assertTrue(np.allclose(_a , _a , atol=1e-3 ) ) def A ( self : Any ) -> List[Any]: '''simple docstring''' import torch _SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE =np.random.rand(100 , 32 ).astype(np.floataa ) _SCREAMING_SNAKE_CASE =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _SCREAMING_SNAKE_CASE =feature_extractor.pad([{'input_features': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) _SCREAMING_SNAKE_CASE =feature_extractor.pad([{'input_features': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def A ( self : Tuple , _a : str ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech _SCREAMING_SNAKE_CASE =ds.sort('id' ).select(range(_a ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def A ( self : List[Any] ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =torch.tensor( [ 0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51, 0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78, 0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54, -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54 ] ) # fmt: on _SCREAMING_SNAKE_CASE =self._load_datasamples(1 ) _SCREAMING_SNAKE_CASE =WhisperFeatureExtractor() _SCREAMING_SNAKE_CASE =feature_extractor(_a , return_tensors='pt' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , _a , atol=1e-4 ) ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE =self._load_datasamples(1 )[0] _SCREAMING_SNAKE_CASE =((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue _SCREAMING_SNAKE_CASE =feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=_a )[0] self.assertTrue(np.all(np.mean(_a ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(_a ) - 1 ) < 1e-3 ) )
114
1
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowercase : """simple docstring""" def __init__(self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=32 , lowerCamelCase_=2 , lowerCamelCase_=3 , lowerCamelCase_=16 , lowerCamelCase_=[1, 2, 1] , lowerCamelCase_=[2, 2, 4] , lowerCamelCase_=2 , lowerCamelCase_=2.0 , lowerCamelCase_=True , lowerCamelCase_=0.0 , lowerCamelCase_=0.0 , lowerCamelCase_=0.1 , lowerCamelCase_="gelu" , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=0.02 , lowerCamelCase_=1E-5 , lowerCamelCase_=True , lowerCamelCase_=None , lowerCamelCase_=True , lowerCamelCase_=10 , lowerCamelCase_=8 , ): """simple docstring""" a = parent a = batch_size a = image_size a = patch_size a = num_channels a = embed_dim a = depths a = num_heads a = window_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = use_absolute_embeddings a = patch_norm a = layer_norm_eps a = initializer_range a = is_training a = scope a = use_labels a = type_sequence_label_size a = encoder_stride def UpperCamelCase_ (self ): """simple docstring""" a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = self.get_config() return config, pixel_values, labels def UpperCamelCase_ (self ): """simple docstring""" return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" a = SwinvaModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() a = model(lowerCamelCase_ ) a = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) a = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" a = SwinvaForMaskedImageModeling(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() a = model(lowerCamelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images a = 1 a = SwinvaForMaskedImageModeling(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a = model(lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" a = self.type_sequence_label_size a = SwinvaForImageClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() a = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ (self ): """simple docstring""" a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _lowercase ( lowerCAmelCase, lowerCAmelCase, unittest.TestCase ): """simple docstring""" __A = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __A = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) __A = False __A = False __A = False __A = False def UpperCamelCase_ (self ): """simple docstring""" a = SwinvaModelTester(self ) a = ConfigTester(self , config_class=lowerCamelCase_ , embed_dim=37 ) def UpperCamelCase_ (self ): """simple docstring""" self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase_ (self ): """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0." ) def UpperCamelCase_ (self ): """simple docstring""" pass @unittest.skip(reason="Swinv2 does not use inputs_embeds" ) def UpperCamelCase_ (self ): """simple docstring""" pass def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(lowerCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase_ , nn.Linear ) ) def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(lowerCamelCase_ ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() a = True for model_class in self.all_model_classes: a = True a = False a = True a = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) a = outputs.attentions a = len(self.model_tester.depths ) self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] a = True a = config.window_size**2 a = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) a = outputs.attentions self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) a = len(lowerCamelCase_ ) # Check attention is always last and order is fine a = True a = True a = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) if hasattr(self.model_tester , "num_hidden_states_types" ): a = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states a = 2 self.assertEqual(out_len + added_hidden_states , len(lowerCamelCase_ ) ) a = outputs.attentions self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" a = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) a = outputs.hidden_states a = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # Swinv2 has a different seq_length a = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) a = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) a = outputs.reshaped_hidden_states self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) a , a , a , a = reshaped_hidden_states[0].shape a = ( reshaped_hidden_states[0].view(lowerCamelCase_ , lowerCamelCase_ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() a = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: a = True self.check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True self.check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() a = 3 a = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) a = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) a = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) a = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: a = True self.check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True self.check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , (padded_height, padded_width) ) def UpperCamelCase_ (self ): """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) @slow def UpperCamelCase_ (self ): """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = SwinvaModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() a = _config_zero_init(lowerCamelCase_ ) for model_class in self.all_model_classes: a = model_class(config=lowerCamelCase_ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _lowercase ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCamelCase_ (self ): """simple docstring""" return ( AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ) if is_vision_available() else None ) @slow def UpperCamelCase_ (self ): """simple docstring""" a = SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ).to( lowerCamelCase_ ) a = self.default_image_processor a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) a = image_processor(images=lowerCamelCase_ , return_tensors="pt" ).to(lowerCamelCase_ ) # forward pass with torch.no_grad(): a = model(**lowerCamelCase_ ) # verify the logits a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) a = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(lowerCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase_ , atol=1E-4 ) )
227
import cmath import math def a( A : float , A : float , A : float , A : float ) -> complex: """simple docstring""" a = math.radians(A ) a = math.radians(A ) # Convert voltage and current to rectangular form a = cmath.rect(A , A ) a = cmath.rect(A , A ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
227
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __magic_name__ ( __UpperCAmelCase , unittest.TestCase ): __A : Tuple = KandinskyVaaPipeline __A : Any = [ "image_embeds", "negative_image_embeds", ] __A : Tuple = ["image_embeds", "negative_image_embeds"] __A : Tuple = [ "generator", "height", "width", "latents", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] __A : Union[str, Any] = False @property def __snake_case ( self : str ): '''simple docstring''' return 3_2 @property def __snake_case ( self : Any ): '''simple docstring''' return 3_2 @property def __snake_case ( self : List[Any] ): '''simple docstring''' return self.time_input_dim @property def __snake_case ( self : Any ): '''simple docstring''' return self.time_input_dim * 4 @property def __snake_case ( self : Optional[int] ): '''simple docstring''' return 1_0_0 @property def __snake_case ( self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase :Optional[Any] = { '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } lowercase :int = UNetaDConditionModel(**snake_case__ ) return model @property def __snake_case ( self : Dict ): '''simple docstring''' return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __snake_case ( self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase :Tuple = VQModel(**self.dummy_movq_kwargs ) return model def __snake_case ( self : List[Any] ): '''simple docstring''' lowercase :Optional[Any] = self.dummy_unet lowercase :List[Any] = self.dummy_movq lowercase :Optional[Any] = DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=snake_case__ , ) lowercase :str = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __snake_case ( self : str , snake_case__ : Any , snake_case__ : str=0 ): '''simple docstring''' lowercase :Tuple = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) lowercase :Union[str, Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( snake_case__ ) if str(snake_case__ ).startswith('''mps''' ): lowercase :Optional[int] = torch.manual_seed(snake_case__ ) else: lowercase :Any = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) lowercase :List[Any] = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __snake_case ( self : List[str] ): '''simple docstring''' lowercase :List[Any] = '''cpu''' lowercase :Tuple = self.get_dummy_components() lowercase :Any = self.pipeline_class(**snake_case__ ) lowercase :List[str] = pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) lowercase :Optional[Any] = pipe(**self.get_dummy_inputs(snake_case__ ) ) lowercase :str = output.images lowercase :Dict = pipe( **self.get_dummy_inputs(snake_case__ ) , return_dict=snake_case__ , )[0] lowercase :Any = image[0, -3:, -3:, -1] lowercase :Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowercase :List[Any] = np.array( [0.6_23_79_76, 1.0, 0.36_44_13_32, 1.0, 0.70_63_96_34, 0.29_87_71_86, 0.85_65_21_25, 0.5_21_68_43, 0.54_45_40_46] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __magic_name__ ( unittest.TestCase ): def __snake_case ( self : int ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Any ): '''simple docstring''' lowercase :Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy''' ) lowercase :int = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(snake_case__ ) lowercase :Tuple = KandinskyVaaPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) lowercase :str = pipeline.to(snake_case__ ) pipeline.set_progress_bar_config(disable=snake_case__ ) lowercase :int = '''red cat, 4k photo''' lowercase :str = torch.Generator(device='''cuda''' ).manual_seed(0 ) lowercase :Union[str, Any] = pipe_prior( snake_case__ , generator=snake_case__ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() lowercase :Tuple = torch.Generator(device='''cuda''' ).manual_seed(0 ) lowercase :List[Any] = pipeline( image_embeds=snake_case__ , negative_image_embeds=snake_case__ , generator=snake_case__ , num_inference_steps=1_0_0 , output_type='''np''' , ) lowercase :Tuple = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(snake_case__ , snake_case__ )
355
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def lowerCamelCase (a_ :int) -> int: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def lowerCamelCase () -> Optional[int]: with parallel_backend('''spark'''): assert ParallelBackendConfig.backend_name == "spark" lowercase :Optional[int] = [1, 2, 3] with pytest.raises(a_): with parallel_backend('''unsupported backend'''): map_nested(a_ , a_ , num_proc=2) with pytest.raises(a_): with parallel_backend('''unsupported backend'''): map_nested(a_ , a_ , num_proc=-1) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('''num_proc''' , [2, -1]) def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]: lowercase :Optional[Any] = [1, 2] lowercase :int = {'''a''': 1, '''b''': 2} lowercase :List[Any] = {'''a''': [1, 2], '''b''': [3, 4]} lowercase :Optional[int] = {'''a''': {'''1''': 1}, '''b''': 2} lowercase :List[Any] = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} lowercase :Optional[int] = [2, 3] lowercase :Tuple = {'''a''': 2, '''b''': 3} lowercase :Union[str, Any] = {'''a''': [2, 3], '''b''': [4, 5]} lowercase :List[str] = {'''a''': {'''1''': 2}, '''b''': 3} lowercase :Union[str, Any] = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} with parallel_backend('''spark'''): assert map_nested(a_ , a_ , num_proc=a_) == expected_map_nested_sa assert map_nested(a_ , a_ , num_proc=a_) == expected_map_nested_sa assert map_nested(a_ , a_ , num_proc=a_) == expected_map_nested_sa assert map_nested(a_ , a_ , num_proc=a_) == expected_map_nested_sa assert map_nested(a_ , a_ , num_proc=a_) == expected_map_nested_sa
172
0
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _UpperCAmelCase : Any = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase ( __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = DebertaVaTokenizer UpperCAmelCase__ = DebertaVaTokenizerFast UpperCAmelCase__ = True UpperCAmelCase__ = True def A_ ( self : Dict ) -> int: super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__ : Optional[Any] = DebertaVaTokenizer(UpperCAmelCase , unk_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : Dict , UpperCAmelCase : Tuple ) -> int: lowerCamelCase__ : Dict = 'this is a test' lowerCamelCase__ : Union[str, Any] = 'this is a test' return input_text, output_text def A_ ( self : Union[str, Any] ) -> Optional[Any]: lowerCamelCase__ : str = '<pad>' lowerCamelCase__ : int = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase ) , UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Optional[int]: lowerCamelCase__ : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '[PAD]' ) self.assertEqual(len(UpperCAmelCase ) , 30001 ) def A_ ( self : Optional[Any] ) -> int: self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def A_ ( self : str ) -> List[str]: # fmt: off lowerCamelCase__ : Union[str, Any] = ' \tHeLLo!how \n Are yoU? ' lowerCamelCase__ : int = ['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on lowerCamelCase__ : Any = DebertaVaTokenizer(UpperCAmelCase , do_lower_case=UpperCAmelCase ) lowerCamelCase__ : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = DebertaVaTokenizerFast(UpperCAmelCase , do_lower_case=UpperCAmelCase ) lowerCamelCase__ : int = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def A_ ( self : Optional[int] ) -> int: pass @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def A_ ( self : Dict ) -> List[str]: pass def A_ ( self : str ) -> Any: # fmt: off lowerCamelCase__ : List[Any] = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : int = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on lowerCamelCase__ : Union[str, Any] = DebertaVaTokenizer(UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : int = DebertaVaTokenizerFast(UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : int ) -> Tuple: # fmt: off lowerCamelCase__ : str = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : Dict = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on lowerCamelCase__ : str = DebertaVaTokenizer(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = DebertaVaTokenizerFast(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> str: # fmt: off lowerCamelCase__ : Any = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : Tuple = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on lowerCamelCase__ : Tuple = DebertaVaTokenizer(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = DebertaVaTokenizerFast(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : List[str] ) -> Tuple: # fmt: off lowerCamelCase__ : Dict = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : List[str] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on lowerCamelCase__ : List[Any] = DebertaVaTokenizer(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : str = DebertaVaTokenizerFast(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Union[str, Any]: # fmt: off lowerCamelCase__ : str = ' \tHeLLo!how \n Are yoU? ' lowerCamelCase__ : Union[str, Any] = ['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on lowerCamelCase__ : str = DebertaVaTokenizer(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : int = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : str = DebertaVaTokenizerFast(UpperCAmelCase , do_lower_case=UpperCAmelCase , split_by_punct=UpperCAmelCase ) lowerCamelCase__ : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Dict ) -> int: lowerCamelCase__ : Optional[Any] = self.get_tokenizer() lowerCamelCase__ : Optional[int] = self.get_rust_tokenizer() lowerCamelCase__ : List[Any] = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) lowerCamelCase__ : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Dict = tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Any = self.get_rust_tokenizer() lowerCamelCase__ : Dict = tokenizer.encode(UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : List[Any] ) -> int: lowerCamelCase__ : List[Any] = 'This is a test' lowerCamelCase__ : Optional[int] = [13, 1, 4398, 25, 21, 1289] lowerCamelCase__ : Dict = ['▁', 'T', 'his', '▁is', '▁a', '▁test'] lowerCamelCase__ : str = ['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] lowerCamelCase__ : Dict = DebertaVaTokenizer(UpperCAmelCase , keep_accents=UpperCAmelCase ) lowerCamelCase__ : Optional[int] = DebertaVaTokenizerFast(UpperCAmelCase , keep_accents=UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer.tokenize(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer.convert_ids_to_tokens(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[str] = rust_tokenizer.tokenize(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : str = rust_tokenizer.convert_ids_to_tokens(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) # fmt: off lowerCamelCase__ : Optional[int] = 'I was born in 92000, and this is falsé.' lowerCamelCase__ : Dict = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] lowerCamelCase__ : List[str] = ['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] lowerCamelCase__ : Dict = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on lowerCamelCase__ : Any = tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Dict = tokenizer.tokenize(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Optional[int] = tokenizer.convert_ids_to_tokens(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[Any] = rust_tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[str] = rust_tokenizer.tokenize(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[Any] = rust_tokenizer.convert_ids_to_tokens(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : int ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = DebertaVaTokenizer(UpperCAmelCase ) lowerCamelCase__ : Dict = tokenizer.encode('sequence builders' ) lowerCamelCase__ : str = tokenizer.encode('multi-sequence build' ) lowerCamelCase__ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase , UpperCAmelCase ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , UpperCAmelCase ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , UpperCAmelCase , ) @slow def A_ ( self : Tuple ) -> int: # fmt: off lowerCamelCase__ : str = {'input_ids': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase , model_name='microsoft/deberta-v2-xlarge' , revision='ad6e42c1532ddf3a15c39246b63f5559d558b670' , )
50
"""simple docstring""" import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class snake_case : def __init__( self : Any , UpperCamelCase__ : int , UpperCamelCase__ : str=1_3 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Any=False , UpperCamelCase__ : str=True , UpperCamelCase__ : List[Any]=9_9 , UpperCamelCase__ : Optional[int]=3_2 , UpperCamelCase__ : List[Any]=5 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : List[str]=3_7 , UpperCamelCase__ : Optional[Any]="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Dict=5_1_2 , UpperCamelCase__ : List[Any]=1_6 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : int=3 , UpperCamelCase__ : Any=4 , UpperCamelCase__ : Optional[int]=None , )-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: Tuple = parent __lowerCAmelCase: Optional[int] = batch_size __lowerCAmelCase: int = seq_length __lowerCAmelCase: Any = is_training __lowerCAmelCase: List[Any] = use_input_mask __lowerCAmelCase: Any = use_token_type_ids __lowerCAmelCase: Dict = use_labels __lowerCAmelCase: Union[str, Any] = vocab_size __lowerCAmelCase: Union[str, Any] = hidden_size __lowerCAmelCase: int = num_hidden_layers __lowerCAmelCase: List[Any] = num_attention_heads __lowerCAmelCase: int = intermediate_size __lowerCAmelCase: Optional[Any] = hidden_act __lowerCAmelCase: Optional[Any] = hidden_dropout_prob __lowerCAmelCase: Optional[int] = attention_probs_dropout_prob __lowerCAmelCase: Any = max_position_embeddings __lowerCAmelCase: Optional[int] = type_vocab_size __lowerCAmelCase: str = type_sequence_label_size __lowerCAmelCase: int = initializer_range __lowerCAmelCase: Dict = num_labels __lowerCAmelCase: Dict = num_choices __lowerCAmelCase: str = scope def lowercase_ ( self : Optional[Any])-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __lowerCAmelCase: List[Any] = None if self.use_input_mask: __lowerCAmelCase: int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCAmelCase: Dict = None if self.use_token_type_ids: __lowerCAmelCase: Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __lowerCAmelCase: str = None __lowerCAmelCase: Any = None __lowerCAmelCase: Dict = None if self.use_labels: __lowerCAmelCase: Any = ids_tensor([self.batch_size] , self.type_sequence_label_size) __lowerCAmelCase: Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __lowerCAmelCase: Optional[int] = ids_tensor([self.batch_size] , self.num_choices) __lowerCAmelCase: Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : str)-> Dict: '''simple docstring''' return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , use_stable_embedding=UpperCamelCase__ , ) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any])-> str: '''simple docstring''' __lowerCAmelCase: List[Any] = OpenLlamaModel(config=UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: Union[str, Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__) __lowerCAmelCase: int = model(UpperCamelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple , )-> Optional[int]: '''simple docstring''' __lowerCAmelCase: Optional[Any] = True __lowerCAmelCase: Any = OpenLlamaModel(UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: List[Any] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , ) __lowerCAmelCase: Optional[int] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , ) __lowerCAmelCase: Optional[Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def lowercase_ ( self : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , )-> Optional[int]: '''simple docstring''' __lowerCAmelCase: str = OpenLlamaForCausalLM(config=UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: Optional[int] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def lowercase_ ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , )-> Tuple: '''simple docstring''' __lowerCAmelCase: Union[str, Any] = True __lowerCAmelCase: Dict = True __lowerCAmelCase: Union[str, Any] = OpenLlamaForCausalLM(config=UpperCamelCase__) model.to(UpperCamelCase__) model.eval() # first forward pass __lowerCAmelCase: Optional[int] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , use_cache=UpperCamelCase__ , ) __lowerCAmelCase: Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __lowerCAmelCase: Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size) __lowerCAmelCase: Optional[int] = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and __lowerCAmelCase: str = torch.cat([input_ids, next_tokens] , dim=-1) __lowerCAmelCase: List[str] = torch.cat([input_mask, next_mask] , dim=-1) __lowerCAmelCase: Union[str, Any] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , output_hidden_states=UpperCamelCase__ , )["hidden_states"][0] __lowerCAmelCase: List[str] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , past_key_values=UpperCamelCase__ , output_hidden_states=UpperCamelCase__ , )["hidden_states"][0] # select random slice __lowerCAmelCase: List[str] = ids_tensor((1,) , output_from_past.shape[-1]).item() __lowerCAmelCase: List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() __lowerCAmelCase: Union[str, Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3)) def lowercase_ ( self : Tuple)-> str: '''simple docstring''' __lowerCAmelCase: Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ): List[Any] = config_and_inputs __lowerCAmelCase: Any = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class snake_case ( __snake_case, __snake_case, __snake_case, unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Tuple = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ : Any = (OpenLlamaForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE_ : Optional[int] = ( { """feature-extraction""": OpenLlamaModel, """text-classification""": OpenLlamaForSequenceClassification, """text-generation""": OpenLlamaForCausalLM, """zero-shot""": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : List[Any] = False def lowercase_ ( self : Dict)-> Union[str, Any]: '''simple docstring''' __lowerCAmelCase: int = OpenLlamaModelTester(self) __lowerCAmelCase: Optional[Any] = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=3_7) def lowercase_ ( self : List[str])-> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any])-> List[Any]: '''simple docstring''' __lowerCAmelCase: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__) def lowercase_ ( self : int)-> str: '''simple docstring''' __lowerCAmelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCAmelCase: Union[str, Any] = type self.model_tester.create_and_check_model(*UpperCamelCase__) def lowercase_ ( self : Tuple)-> Optional[Any]: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase: Dict = 3 __lowerCAmelCase: Optional[Any] = input_dict["input_ids"] __lowerCAmelCase: Optional[Any] = input_ids.ne(1).to(UpperCamelCase__) __lowerCAmelCase: Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) __lowerCAmelCase: Dict = OpenLlamaForSequenceClassification(UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: Optional[int] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def lowercase_ ( self : Dict)-> Tuple: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase: int = 3 __lowerCAmelCase: Dict = "single_label_classification" __lowerCAmelCase: str = input_dict["input_ids"] __lowerCAmelCase: Tuple = input_ids.ne(1).to(UpperCamelCase__) __lowerCAmelCase: Tuple = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) __lowerCAmelCase: List[Any] = OpenLlamaForSequenceClassification(UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: Optional[Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def lowercase_ ( self : Optional[int])-> Any: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: str = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase: Tuple = 3 __lowerCAmelCase: Any = "multi_label_classification" __lowerCAmelCase: str = input_dict["input_ids"] __lowerCAmelCase: Optional[int] = input_ids.ne(1).to(UpperCamelCase__) __lowerCAmelCase: Optional[int] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) __lowerCAmelCase: Dict = OpenLlamaForSequenceClassification(UpperCamelCase__) model.to(UpperCamelCase__) model.eval() __lowerCAmelCase: Union[str, Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip("Open-Llama buffers include complex numbers, which breaks this test") def lowercase_ ( self : Any)-> Tuple: '''simple docstring''' pass @parameterized.expand([("linear",), ("dynamic",)]) def lowercase_ ( self : Any , UpperCamelCase__ : List[str])-> Dict: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase: Any = ids_tensor([1, 1_0] , config.vocab_size) __lowerCAmelCase: Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(4_2) # Fixed seed at init time so the two models get the same random weights __lowerCAmelCase: List[Any] = OpenLlamaModel(UpperCamelCase__) original_model.to(UpperCamelCase__) original_model.eval() __lowerCAmelCase: int = original_model(UpperCamelCase__).last_hidden_state __lowerCAmelCase: str = original_model(UpperCamelCase__).last_hidden_state set_seed(4_2) # Fixed seed at init time so the two models get the same random weights __lowerCAmelCase: Dict = {"type": scaling_type, "factor": 10.0} __lowerCAmelCase: List[str] = OpenLlamaModel(UpperCamelCase__) scaled_model.to(UpperCamelCase__) scaled_model.eval() __lowerCAmelCase: Dict = scaled_model(UpperCamelCase__).last_hidden_state __lowerCAmelCase: Any = scaled_model(UpperCamelCase__).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5)) else: self.assertFalse(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5))
217
0
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase_ ( UpperCamelCase__ ): """simple docstring""" _lowerCAmelCase : Dict = ["""image_processor""", """tokenizer"""] _lowerCAmelCase : Tuple = """Pix2StructImageProcessor""" _lowerCAmelCase : Union[str, Any] = ("""T5Tokenizer""", """T5TokenizerFast""") def __init__( self , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" snake_case = False super().__init__(__lowerCamelCase , __lowerCamelCase ) def __call__( self , lowerCAmelCase=None , lowerCAmelCase = None , lowerCAmelCase = True , lowerCAmelCase = False , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = 20_48 , lowerCAmelCase = 0 , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = False , lowerCAmelCase = False , lowerCAmelCase = False , lowerCAmelCase = False , lowerCAmelCase = False , lowerCAmelCase = True , lowerCAmelCase = None , **lowerCAmelCase , ): """simple docstring""" if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None and not self.image_processor.is_vqa: snake_case = self.tokenizer snake_case = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values snake_case = self.image_processor( __lowerCamelCase , return_tensors=__lowerCamelCase , max_patches=__lowerCamelCase , **__lowerCamelCase ) else: # add pixel_values and bbox snake_case = self.image_processor( __lowerCamelCase , return_tensors=__lowerCamelCase , max_patches=__lowerCamelCase , header_text=__lowerCamelCase , **__lowerCamelCase ) if text is not None and not self.image_processor.is_vqa: snake_case = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) if "attention_mask" in text_encoding: snake_case = text_encoding.pop('attention_mask' ) if "input_ids" in text_encoding: snake_case = text_encoding.pop('input_ids' ) else: snake_case = None if text_encoding is not None: encoding_image_processor.update(__lowerCamelCase ) return encoding_image_processor def snake_case ( self , *lowerCAmelCase , **lowerCAmelCase ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def snake_case ( self , *lowerCAmelCase , **lowerCAmelCase ): """simple docstring""" return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property def snake_case ( self ): """simple docstring""" snake_case = self.tokenizer.model_input_names snake_case = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
367
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def lowerCAmelCase__ ( _UpperCamelCase : int = 8 ) -> str: """simple docstring""" snake_case = ascii_letters + digits + punctuation return "".join(secrets.choice(_UpperCamelCase ) for _ in range(_UpperCamelCase ) ) def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int ) -> str: """simple docstring""" i -= len(_UpperCamelCase ) snake_case = i // 3 snake_case = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case = ( chars_incl + random(_UpperCamelCase , quotient + remainder ) + random(_UpperCamelCase , _UpperCamelCase ) + random(_UpperCamelCase , _UpperCamelCase ) ) snake_case = list(_UpperCamelCase ) shuffle(_UpperCamelCase ) return "".join(_UpperCamelCase ) # random is a generalised function for letters, characters and numbers def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int ) -> str: """simple docstring""" return "".join(secrets.choice(_UpperCamelCase ) for _ in range(_UpperCamelCase ) ) def lowerCAmelCase__ ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[Any] ) -> List[Any]: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] ) -> Any: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : Dict , _UpperCamelCase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int = 8 ) -> bool: """simple docstring""" if len(_UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False snake_case = any(char in ascii_uppercase for char in password ) snake_case = any(char in ascii_lowercase for char in password ) snake_case = any(char in digits for char in password ) snake_case = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def lowerCAmelCase__ ( ) -> Any: """simple docstring""" snake_case = int(input('Please indicate the max length of your password: ' ).strip() ) snake_case = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' , password_generator(_UpperCamelCase ) ) print( 'Alternative Password generated:' , alternative_password_generator(_UpperCamelCase , _UpperCamelCase ) , ) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
149
0
'''simple docstring''' import os from pathlib import Path def lowercase__ ( ) -> str: """simple docstring""" from torch.utils.cpp_extension import load __UpperCamelCase = Path(__lowercase ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' __UpperCamelCase = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , __lowercase , with_cuda=__lowercase , extra_include_paths=[str(__lowercase )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
53
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCamelCase : '''simple docstring''' def __init__( self: Dict , snake_case: Optional[Any] , snake_case: Tuple=13 , snake_case: Any=32 , snake_case: Union[str, Any]=2 , snake_case: Tuple=3 , snake_case: Union[str, Any]=16 , snake_case: Union[str, Any]=[1, 2, 1] , snake_case: Optional[Any]=[2, 2, 4] , snake_case: str=2 , snake_case: List[str]=2.0 , snake_case: Optional[int]=True , snake_case: Union[str, Any]=0.0 , snake_case: Optional[int]=0.0 , snake_case: Optional[Any]=0.1 , snake_case: List[str]="gelu" , snake_case: Any=False , snake_case: Optional[Any]=True , snake_case: Optional[int]=0.0_2 , snake_case: Any=1E-5 , snake_case: Optional[int]=True , snake_case: int=None , snake_case: Any=True , snake_case: str=10 , snake_case: Optional[Any]=8 , snake_case: Union[str, Any]=["stage1", "stage2", "stage3"] , snake_case: Tuple=[1, 2, 3] , ) -> Dict: snake_case_ :Dict = parent snake_case_ :List[Any] = batch_size snake_case_ :Dict = image_size snake_case_ :Dict = patch_size snake_case_ :Tuple = num_channels snake_case_ :List[Any] = embed_dim snake_case_ :List[str] = depths snake_case_ :str = num_heads snake_case_ :Tuple = window_size snake_case_ :Tuple = mlp_ratio snake_case_ :int = qkv_bias snake_case_ :Tuple = hidden_dropout_prob snake_case_ :Optional[Any] = attention_probs_dropout_prob snake_case_ :Dict = drop_path_rate snake_case_ :Any = hidden_act snake_case_ :Any = use_absolute_embeddings snake_case_ :int = patch_norm snake_case_ :List[Any] = layer_norm_eps snake_case_ :Tuple = initializer_range snake_case_ :str = is_training snake_case_ :int = scope snake_case_ :Tuple = use_labels snake_case_ :Tuple = type_sequence_label_size snake_case_ :str = encoder_stride snake_case_ :List[Any] = out_features snake_case_ :str = out_indices def lowerCAmelCase_ ( self: Tuple ) -> Dict: snake_case_ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ :str = None if self.use_labels: snake_case_ :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ :Union[str, Any] = self.get_config() return config, pixel_values, labels def lowerCAmelCase_ ( self: int ) -> Optional[Any]: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def lowerCAmelCase_ ( self: List[Any] , snake_case: str , snake_case: int , snake_case: List[str] ) -> Any: snake_case_ :Dict = MaskFormerSwinModel(config=snake_case ) model.to(snake_case ) model.eval() snake_case_ :Tuple = model(snake_case ) snake_case_ :Dict = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case_ :Any = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def lowerCAmelCase_ ( self: Optional[Any] , snake_case: int , snake_case: List[str] , snake_case: Tuple ) -> Union[str, Any]: snake_case_ :Any = MaskFormerSwinBackbone(config=snake_case ) model.to(snake_case ) model.eval() snake_case_ :Optional[Any] = model(snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(snake_case ): snake_case_ :Optional[Any] = ["""stem"""] snake_case_ :str = MaskFormerSwinBackbone(config=snake_case ) def lowerCAmelCase_ ( self: List[str] ) -> Optional[Any]: snake_case_ :Optional[int] = self.prepare_config_and_inputs() snake_case_, snake_case_, snake_case_ :str = config_and_inputs snake_case_ :Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : Union[str, Any] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _A : str = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} _A : List[str] = False _A : Any = False _A : Dict = False _A : List[Any] = False _A : Optional[int] = False def lowerCAmelCase_ ( self: Dict ) -> Any: snake_case_ :str = MaskFormerSwinModelTester(self ) snake_case_ :Optional[Any] = ConfigTester(self , config_class=snake_case , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def lowerCAmelCase_ ( self: List[str] ) -> Optional[int]: pass def lowerCAmelCase_ ( self: Union[str, Any] ) -> Dict: 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 lowerCAmelCase_ ( self: Any ) -> Tuple: return def lowerCAmelCase_ ( self: Any ) -> Any: snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def lowerCAmelCase_ ( self: Union[str, Any] ) -> int: snake_case_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*snake_case ) @unittest.skip("""Swin does not use inputs_embeds""" ) def lowerCAmelCase_ ( self: str ) -> List[str]: pass @unittest.skip("""Swin does not support feedforward chunking""" ) def lowerCAmelCase_ ( self: int ) -> Optional[int]: pass def lowerCAmelCase_ ( self: List[str] ) -> List[Any]: snake_case_, snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :str = model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ :Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case , nn.Linear ) ) def lowerCAmelCase_ ( self: Tuple ) -> Dict: snake_case_, snake_case_ :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :Optional[int] = model_class(snake_case ) snake_case_ :str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ :str = [*signature.parameters.keys()] snake_case_ :str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def lowerCAmelCase_ ( self: List[Any] ) -> List[Any]: pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def lowerCAmelCase_ ( self: Dict ) -> List[Any]: pass def lowerCAmelCase_ ( self: Union[str, Any] , snake_case: Union[str, Any] , snake_case: int , snake_case: Any , snake_case: List[str] ) -> str: snake_case_ :List[str] = model_class(snake_case ) model.to(snake_case ) model.eval() with torch.no_grad(): snake_case_ :List[Any] = model(**self._prepare_for_class(snake_case , snake_case ) ) snake_case_ :Any = outputs.hidden_states snake_case_ :Optional[int] = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(snake_case ) , snake_case ) # Swin has a different seq_length snake_case_ :str = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ :int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def lowerCAmelCase_ ( self: List[Any] ) -> Optional[int]: snake_case_, snake_case_ :Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case_ :Tuple = True self.check_hidden_states_output(snake_case , snake_case , snake_case , snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ :List[Any] = True self.check_hidden_states_output(snake_case , snake_case , snake_case , snake_case ) def lowerCAmelCase_ ( self: Optional[Any] ) -> Tuple: snake_case_, snake_case_ :int = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :List[Any] = 3 snake_case_ :List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case_ :Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ :Tuple = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case_ :List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case_ :str = True self.check_hidden_states_output(snake_case , snake_case , snake_case , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ :Any = True self.check_hidden_states_output(snake_case , snake_case , snake_case , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[str]: pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowerCAmelCase_ ( self: List[str] ) -> str: pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowerCAmelCase_ ( self: str ) -> List[Any]: pass def lowerCAmelCase_ ( self: Union[str, Any] ) -> Optional[Any]: snake_case_, snake_case_ :Dict = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(snake_case: str ): snake_case_ :Optional[int] = 0 return t def check_equivalence(snake_case: List[Any] , snake_case: Union[str, Any] , snake_case: int , snake_case: Tuple={} ): with torch.no_grad(): snake_case_ :List[Any] = model(**snake_case , return_dict=snake_case , **snake_case ) snake_case_ :Any = model(**snake_case , return_dict=snake_case , **snake_case ).to_tuple() def recursive_check(snake_case: List[Any] , snake_case: int ): if isinstance(snake_case , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(snake_case , snake_case ): recursive_check(snake_case , snake_case ) elif isinstance(snake_case , snake_case ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(snake_case , snake_case ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(snake_case ) , set_nan_tensor_to_zero(snake_case ) , atol=1E-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" f""" {torch.isnan(snake_case ).any()} and `inf`: {torch.isinf(snake_case )}. Dict has""" f""" `nan`: {torch.isnan(snake_case ).any()} and `inf`: {torch.isinf(snake_case )}.""" ) , ) recursive_check(snake_case , snake_case ) for model_class in self.all_model_classes: snake_case_ :int = model_class(snake_case ) model.to(snake_case ) model.eval() snake_case_ :Any = self._prepare_for_class(snake_case , snake_case ) snake_case_ :List[Any] = self._prepare_for_class(snake_case , snake_case ) check_equivalence(snake_case , snake_case , snake_case ) snake_case_ :Tuple = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) snake_case_ :Dict = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) check_equivalence(snake_case , snake_case , snake_case ) snake_case_ :Tuple = self._prepare_for_class(snake_case , snake_case ) snake_case_ :Any = self._prepare_for_class(snake_case , snake_case ) check_equivalence(snake_case , snake_case , snake_case , {"""output_hidden_states""": True} ) snake_case_ :Dict = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) snake_case_ :List[str] = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) check_equivalence(snake_case , snake_case , snake_case , {"""output_hidden_states""": True} ) @require_torch class lowerCamelCase ( unittest.TestCase , _lowerCAmelCase ): '''simple docstring''' _A : int = (MaskFormerSwinBackbone,) if is_torch_available() else () _A : Tuple = MaskFormerSwinConfig def lowerCAmelCase_ ( self: List[str] ) -> Optional[int]: snake_case_ :Optional[Any] = MaskFormerSwinModelTester(self ) def lowerCAmelCase_ ( self: int ) -> Optional[int]: snake_case_, snake_case_ :Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :Tuple = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: snake_case_ :List[str] = backbone_class(snake_case ) backbone.to(snake_case ) backbone.eval() snake_case_ :List[Any] = backbone(**snake_case ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , snake_case ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True snake_case_ :Union[str, Any] = backbone(**snake_case , output_hidden_states=snake_case ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) snake_case_, snake_case_, snake_case_ :List[Any] = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: snake_case_ :List[Any] = backbone(**snake_case , output_attentions=snake_case ) self.assertIsNotNone(outputs.attentions )
66
0
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging _lowerCamelCase : List[Any] = logging.get_logger(__name__) class UpperCamelCase_ ( __snake_case ): '''simple docstring''' UpperCAmelCase__ = """linear""" UpperCAmelCase__ = """cosine""" UpperCAmelCase__ = """cosine_with_restarts""" UpperCAmelCase__ = """polynomial""" UpperCAmelCase__ = """constant""" UpperCAmelCase__ = """constant_with_warmup""" UpperCAmelCase__ = """piecewise_constant""" def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = -1 ) -> Dict: """simple docstring""" return LambdaLR(__SCREAMING_SNAKE_CASE , lambda lowercase_ : 1 , last_epoch=__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ = -1 ) -> int: """simple docstring""" def lr_lambda(lowercase_ ): if current_step < num_warmup_steps: return float(__SCREAMING_SNAKE_CASE ) / float(max(1.0 , __SCREAMING_SNAKE_CASE ) ) return 1.0 return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ = -1 ) -> Optional[Any]: """simple docstring""" A__ = {} A__ = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: A__ = rule_str.split(''':''' ) A__ = int(__SCREAMING_SNAKE_CASE ) A__ = float(__SCREAMING_SNAKE_CASE ) A__ = value A__ = float(rule_list[-1] ) def create_rules_function(lowercase_ , lowercase_ ): def rule_func(lowercase_ ) -> float: A__ = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(__SCREAMING_SNAKE_CASE ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func A__ = create_rules_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=-1 ) -> Optional[Any]: """simple docstring""" def lr_lambda(lowercase_ ): if current_step < num_warmup_steps: return float(__SCREAMING_SNAKE_CASE ) / float(max(1 , __SCREAMING_SNAKE_CASE ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ = 0.5 , lowercase_ = -1 ) -> Dict: """simple docstring""" def lr_lambda(lowercase_ ): if current_step < num_warmup_steps: return float(__SCREAMING_SNAKE_CASE ) / float(max(1 , __SCREAMING_SNAKE_CASE ) ) A__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(__SCREAMING_SNAKE_CASE ) * 2.0 * progress )) ) return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ = 1 , lowercase_ = -1 ) -> Tuple: """simple docstring""" def lr_lambda(lowercase_ ): if current_step < num_warmup_steps: return float(__SCREAMING_SNAKE_CASE ) / float(max(1 , __SCREAMING_SNAKE_CASE ) ) A__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(__SCREAMING_SNAKE_CASE ) * progress) % 1.0) )) ) return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=1E-7 , lowercase_=1.0 , lowercase_=-1 ) -> int: """simple docstring""" A__ = optimizer.defaults["lr"] if not (lr_init > lr_end): raise ValueError(f"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(lowercase_ ): if current_step < num_warmup_steps: return float(__SCREAMING_SNAKE_CASE ) / float(max(1 , __SCREAMING_SNAKE_CASE ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: A__ = lr_init - lr_end A__ = num_training_steps - num_warmup_steps A__ = 1 - (current_step - num_warmup_steps) / decay_steps A__ = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _lowerCamelCase : Dict = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = 1 , lowercase_ = 1.0 , lowercase_ = -1 , ) -> Dict: """simple docstring""" A__ = SchedulerType(__SCREAMING_SNAKE_CASE ) A__ = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(__SCREAMING_SNAKE_CASE , step_rules=__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(__SCREAMING_SNAKE_CASE , num_warmup_steps=__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( __SCREAMING_SNAKE_CASE , num_warmup_steps=__SCREAMING_SNAKE_CASE , num_training_steps=__SCREAMING_SNAKE_CASE , num_cycles=__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( __SCREAMING_SNAKE_CASE , num_warmup_steps=__SCREAMING_SNAKE_CASE , num_training_steps=__SCREAMING_SNAKE_CASE , power=__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE , ) return schedule_func( __SCREAMING_SNAKE_CASE , num_warmup_steps=__SCREAMING_SNAKE_CASE , num_training_steps=__SCREAMING_SNAKE_CASE , last_epoch=__SCREAMING_SNAKE_CASE )
370
from __future__ import annotations import queue class UpperCamelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase__ : Dict) ->Any: '''simple docstring''' A__ = data A__ = None A__ = None def SCREAMING_SNAKE_CASE ( ) -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) A__ = input('''Enter the value of the root node: ''' ).strip().lower() A__ = queue.Queue() A__ = TreeNode(int(lowercase_ ) ) q.put(lowercase_ ) while not q.empty(): A__ = q.get() A__ = f"""Enter the left node of {node_found.data}: """ A__ = input(lowercase_ ).strip().lower() or '''n''' if check == "n": return tree_node A__ = TreeNode(int(lowercase_ ) ) A__ = left_node q.put(lowercase_ ) A__ = f"""Enter the right node of {node_found.data}: """ A__ = input(lowercase_ ).strip().lower() or '''n''' if check == "n": return tree_node A__ = TreeNode(int(lowercase_ ) ) A__ = right_node q.put(lowercase_ ) raise def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return A__ = queue.Queue() q.put(lowercase_ ) while not q.empty(): A__ = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return A__ = queue.Queue() q.put(lowercase_ ) while not q.empty(): A__ = [] while not q.empty(): A__ = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return A__ = [] A__ = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(lowercase_ ) A__ = n.left # end of while means current node doesn't have left child A__ = stack.pop() # start to traverse its right child A__ = n.right def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return A__ = [] A__ = node while n or stack: while n: stack.append(lowercase_ ) A__ = n.left A__ = stack.pop() print(n.data , end=''',''' ) A__ = n.right def SCREAMING_SNAKE_CASE ( lowercase_ ) -> None: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ) or not node: return A__ , A__ = [], [] A__ = node stacka.append(lowercase_ ) while stacka: # to find the reversed order of post order, store it in stack2 A__ = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(lowercase_ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def SCREAMING_SNAKE_CASE ( lowercase_ = "" , lowercase_=50 , lowercase_="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char A__ , A__ = divmod(width - len(lowercase_ ) - 2 , 2 ) return f"""{left * char} {s} {(left + extra) * char}""" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) _lowerCamelCase : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
231
0
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BarthezTokenizer __SCREAMING_SNAKE_CASE : Dict = BarthezTokenizerFast __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : Union[str, Any] = True def __lowerCAmelCase ( self ) ->Dict: super().setUp() SCREAMING_SNAKE_CASE : int = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Tuple = '''<pad>''' SCREAMING_SNAKE_CASE : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(_lowerCamelCase ) , 10_1122 ) def __lowerCAmelCase ( self ) ->List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 10_1122 ) @require_torch def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : int = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] SCREAMING_SNAKE_CASE : Tuple = [0, 57, 3018, 7_0307, 91, 2] SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer( _lowerCamelCase , max_length=len(_lowerCamelCase ) , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE : Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Dict = '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = rust_tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @slow def __lowerCAmelCase ( self ) ->Tuple: # fmt: off SCREAMING_SNAKE_CASE : List[Any] = {'''input_ids''': [[0, 490, 1_4328, 4507, 354, 47, 4_3669, 95, 25, 7_8117, 2_0215, 1_9779, 190, 22, 400, 4, 3_5343, 8_0310, 603, 86, 2_4937, 105, 3_3438, 9_4762, 196, 3_9642, 7, 15, 1_5933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1_0534, 87, 25, 66, 3358, 196, 5_5289, 8, 8_2961, 81, 2204, 7_5203, 7, 15, 763, 1_2956, 216, 178, 1_4328, 9595, 1377, 6_9693, 7, 448, 7_1021, 196, 1_8106, 1437, 1_3974, 108, 9083, 4, 4_9315, 7, 39, 86, 1326, 2793, 4_6333, 4, 448, 196, 7_4588, 7, 4_9315, 7, 39, 21, 822, 3_8470, 74, 21, 6_6723, 6_2480, 8, 2_2050, 5, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. SCREAMING_SNAKE_CASE : List[str] = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=_lowerCamelCase , )
313
from abc import ABC, abstractmethod from typing import List, Optional class a_ ( a__ ): """simple docstring""" def __init__( self ) ->List[str]: # test for the above condition self.test() def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = False while not completed: if counter == 1: self.reset() SCREAMING_SNAKE_CASE : List[Any] = self.advance() if not self.does_advance(_lowerCamelCase ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.update(_lowerCamelCase ) counter += 1 if counter > 1_0000: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def __lowerCAmelCase ( self ) ->Optional[int]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __lowerCAmelCase ( self ) ->Optional[Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __lowerCAmelCase ( self ) ->Union[str, Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->Any: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->int: super(_lowerCamelCase , self ).__init__() if not isinstance(_lowerCamelCase , _lowerCamelCase ) or len(_lowerCamelCase ) == 0: raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(_lowerCamelCase , _lowerCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(F"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) SCREAMING_SNAKE_CASE : Optional[Any] = token_ids SCREAMING_SNAKE_CASE : Union[str, Any] = len(self.token_ids ) SCREAMING_SNAKE_CASE : Any = -1 # the index of the currently fulfilled step SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->List[Any]: if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(_lowerCamelCase )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : Any = False SCREAMING_SNAKE_CASE : List[Any] = False if self.does_advance(_lowerCamelCase ): self.fulfilled_idx += 1 SCREAMING_SNAKE_CASE : str = True if self.fulfilled_idx == (self.seqlen - 1): SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : Union[str, Any] = completed else: # failed to make progress. SCREAMING_SNAKE_CASE : Dict = True self.reset() return stepped, completed, reset def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Union[str, Any] = 0 def __lowerCAmelCase ( self ) ->Any: return self.seqlen - (self.fulfilled_idx + 1) def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->Dict: SCREAMING_SNAKE_CASE : Any = PhrasalConstraint(self.token_ids ) if stateful: SCREAMING_SNAKE_CASE : Dict = self.seqlen SCREAMING_SNAKE_CASE : int = self.fulfilled_idx SCREAMING_SNAKE_CASE : Tuple = self.completed return new_constraint class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=True ) ->Dict: SCREAMING_SNAKE_CASE : Any = max([len(_lowerCamelCase ) for one in nested_token_ids] ) SCREAMING_SNAKE_CASE : List[str] = {} for token_ids in nested_token_ids: SCREAMING_SNAKE_CASE : Optional[Any] = root for tidx, token_id in enumerate(_lowerCamelCase ): if token_id not in level: SCREAMING_SNAKE_CASE : Any = {} SCREAMING_SNAKE_CASE : Tuple = level[token_id] if no_subsets and self.has_subsets(_lowerCamelCase , _lowerCamelCase ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F""" {nested_token_ids}.""" ) SCREAMING_SNAKE_CASE : List[Any] = root def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : List[Any] = self.trie for current_token in current_seq: SCREAMING_SNAKE_CASE : int = start[current_token] SCREAMING_SNAKE_CASE : Optional[int] = list(start.keys() ) return next_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : Any = self.next_tokens(_lowerCamelCase ) return len(_lowerCamelCase ) == 0 def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Any = list(root.values() ) if len(_lowerCamelCase ) == 0: return 1 else: return sum([self.count_leaves(_lowerCamelCase ) for nn in next_nodes] ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = self.count_leaves(_lowerCamelCase ) return len(_lowerCamelCase ) != leaf_count class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->str: super(_lowerCamelCase , self ).__init__() if not isinstance(_lowerCamelCase , _lowerCamelCase ) or len(_lowerCamelCase ) == 0: raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(_lowerCamelCase , _lowerCamelCase ) for token_ids in nested_token_ids ): raise ValueError(F"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(_lowerCamelCase , _lowerCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) SCREAMING_SNAKE_CASE : List[Any] = DisjunctiveTrie(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = nested_token_ids SCREAMING_SNAKE_CASE : Optional[int] = self.trie.max_height SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : Optional[int] = False def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : str = self.trie.next_tokens(self.current_seq ) if len(_lowerCamelCase ) == 0: return None else: return token_list def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[str] = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Any: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Union[str, Any] = False if self.does_advance(_lowerCamelCase ): self.current_seq.append(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = True else: SCREAMING_SNAKE_CASE : Dict = True self.reset() SCREAMING_SNAKE_CASE : Any = self.trie.reached_leaf(self.current_seq ) SCREAMING_SNAKE_CASE : List[Any] = completed return stepped, completed, reset def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Any = False SCREAMING_SNAKE_CASE : List[Any] = [] def __lowerCAmelCase ( self ) ->Optional[Any]: if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->List[str]: SCREAMING_SNAKE_CASE : str = DisjunctiveConstraint(self.token_ids ) if stateful: SCREAMING_SNAKE_CASE : str = self.seqlen SCREAMING_SNAKE_CASE : int = self.current_seq SCREAMING_SNAKE_CASE : Optional[int] = self.completed return new_constraint class a_ : """simple docstring""" def __init__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : List[Any] = constraints # max # of steps required to fulfill a given constraint SCREAMING_SNAKE_CASE : str = max([c.seqlen for c in constraints] ) SCREAMING_SNAKE_CASE : List[str] = len(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = False self.init_state() def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Tuple = [constraint.copy(stateful=_lowerCamelCase ) for constraint in self.constraints] def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : str = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Tuple = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" SCREAMING_SNAKE_CASE : Optional[int] = constraint.advance() if isinstance(_lowerCamelCase , _lowerCamelCase ): token_list.append(_lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): token_list.extend(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[str] = self.inprogress_constraint.advance() if isinstance(_lowerCamelCase , _lowerCamelCase ): token_list.append(_lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): token_list.extend(_lowerCamelCase ) if len(_lowerCamelCase ) == 0: return None else: return token_list def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.add(_lowerCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[Any]: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = False, False if self.completed: SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Optional[int] = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.inprogress_constraint.update(_lowerCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) SCREAMING_SNAKE_CASE : str = None if len(self.pending_constraints ) == 0: # we're done! SCREAMING_SNAKE_CASE : Optional[Any] = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(_lowerCamelCase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pending_constraint.update(_lowerCamelCase ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = None if not complete and stepped: SCREAMING_SNAKE_CASE : Optional[Any] = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. SCREAMING_SNAKE_CASE : str = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def __lowerCAmelCase ( self , _lowerCamelCase=True ) ->str: SCREAMING_SNAKE_CASE : Dict = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: SCREAMING_SNAKE_CASE : str = [ constraint.copy(stateful=_lowerCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.inprogress_constraint.copy(stateful=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [constraint.copy() for constraint in self.pending_constraints] return new_state
313
1
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowerCamelCase ( lowercase : NDArray[floataa] , lowercase : NDArray[floataa] , lowercase : list[int] , lowercase : int , ) -> list[float]: _a = coefficient_matrix.shape _a = constant_matrix.shape if rowsa != colsa: _a = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(UpperCAmelCase__ ) if colsa != 1: _a = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(UpperCAmelCase__ ) if rowsa != rowsa: _a = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(UpperCAmelCase__ ) if len(UpperCAmelCase__ ) != rowsa: _a = ( """Number of initial values must be equal to number of rows in coefficient """ F'matrix but received {len(UpperCAmelCase__ )} and {rowsa}' ) raise ValueError(UpperCAmelCase__ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) _a = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) _a = table.shape strictly_diagonally_dominant(UpperCAmelCase__ ) # Iterates the whole matrix for given number of times for _ in range(UpperCAmelCase__ ): _a = [] for row in range(UpperCAmelCase__ ): _a = 0 for col in range(UpperCAmelCase__ ): if col == row: _a = table[row][col] elif col == cols - 1: _a = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] _a = (temp + val) / denom new_val.append(UpperCAmelCase__ ) _a = new_val return [float(UpperCAmelCase__ ) for i in new_val] def _lowerCamelCase ( lowercase : NDArray[floataa] ) -> bool: _a = table.shape _a = True for i in range(0 , UpperCAmelCase__ ): _a = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
371
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): lowerCAmelCase_ : str = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ : Union[str, Any] = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = (images / 2 + 0.5).clamp(0 , 1 ) _a = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _a = numpy_to_pil(lowercase ) return images def _lowerCamelCase ( lowercase : int ) -> List[Any]: if images.ndim == 3: _a = images[None, ...] _a = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _a = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: _a = [Image.fromarray(lowercase ) for image in images] return pil_images
346
0
__lowerCamelCase : Union[str, Any] = { """meter""": """m""", """kilometer""": """km""", """megametre""": """Mm""", """gigametre""": """Gm""", """terametre""": """Tm""", """petametre""": """Pm""", """exametre""": """Em""", """zettametre""": """Zm""", """yottametre""": """Ym""", } # Exponent of the factor(meter) __lowerCamelCase : int = { """m""": 0, """km""": 3, """Mm""": 6, """Gm""": 9, """Tm""": 12, """Pm""": 15, """Em""": 18, """Zm""": 21, """Ym""": 24, } def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> float: UpperCamelCase : Tuple = from_type.lower().strip("s" ) UpperCamelCase : int = to_type.lower().strip("s" ) UpperCamelCase : Tuple = UNIT_SYMBOL.get(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Union[str, Any] = UNIT_SYMBOL.get(_lowerCAmelCase , _lowerCAmelCase ) if from_sanitized not in METRIC_CONVERSION: UpperCamelCase : Tuple = ( F"""Invalid 'from_type' value: {from_type!r}.\n""" F"""Conversion abbreviations are: {", ".join(_lowerCAmelCase )}""" ) raise ValueError(_lowerCAmelCase ) if to_sanitized not in METRIC_CONVERSION: UpperCamelCase : List[str] = ( F"""Invalid 'to_type' value: {to_type!r}.\n""" F"""Conversion abbreviations are: {", ".join(_lowerCAmelCase )}""" ) raise ValueError(_lowerCAmelCase ) UpperCamelCase : List[Any] = METRIC_CONVERSION[from_sanitized] UpperCamelCase : Optional[Any] = METRIC_CONVERSION[to_sanitized] UpperCamelCase : Any = 1 if from_exponent > to_exponent: UpperCamelCase : List[Any] = from_exponent - to_exponent else: UpperCamelCase : List[Any] = -(to_exponent - from_exponent) return value * pow(10 , _lowerCAmelCase ) if __name__ == "__main__": from doctest import testmod testmod()
52
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
0
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __A : int = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> str: '''simple docstring''' return (preds == labels).mean() @dataclass class __A : lowerCAmelCase_ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowerCAmelCase_ : Optional[str] = field( default=lowerCAmelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) lowerCAmelCase_ : Optional[str] = field( default=lowerCAmelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) lowerCAmelCase_ : Optional[str] = field( default=lowerCAmelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __A : lowerCAmelCase_ : str = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} ) lowerCAmelCase_ : str = field(metadata={"help": "Should contain the data files for the task."} ) lowerCAmelCase_ : int = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCAmelCase_ : bool = field( default=lowerCAmelCase , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def SCREAMING_SNAKE_CASE__ ( ) -> int: '''simple docstring''' lowerCAmelCase : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ' --overwrite_output_dir to overcome.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s', _UpperCAmelCase ) # Set seed set_seed(training_args.seed ) try: lowerCAmelCase : str = processors[data_args.task_name]() lowerCAmelCase : int = processor.get_labels() lowerCAmelCase : Dict = len(_UpperCAmelCase ) except KeyError: raise ValueError('Task not found: %s' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase : Dict = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=_UpperCAmelCase, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) lowerCAmelCase : str = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('.ckpt' in model_args.model_name_or_path ), config=_UpperCAmelCase, cache_dir=model_args.cache_dir, ) # Get datasets lowerCAmelCase : str = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=_UpperCAmelCase, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) lowerCAmelCase : Optional[Any] = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=_UpperCAmelCase, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(_UpperCAmelCase ) -> Dict: lowerCAmelCase : int = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(_UpperCAmelCase, p.label_ids )} # Data collator lowerCAmelCase : Any = DataCollatorWithPadding(_UpperCAmelCase, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase : Union[str, Any] = Trainer( model=_UpperCAmelCase, args=_UpperCAmelCase, train_dataset=_UpperCAmelCase, eval_dataset=_UpperCAmelCase, compute_metrics=_UpperCAmelCase, data_collator=_UpperCAmelCase, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase : int = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) lowerCAmelCase : List[Any] = trainer.evaluate() lowerCAmelCase : Any = os.path.join(training_args.output_dir, 'eval_results.txt' ) if trainer.is_world_master(): with open(_UpperCAmelCase, 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s', _UpperCAmelCase, _UpperCAmelCase ) writer.write('%s = %s\n' % (key, value) ) results.update(_UpperCAmelCase ) return results def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' main() if __name__ == "__main__": main()
323
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, ) __A : List[Any] = { '''configuration_xlm_roberta''': [ '''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaConfig''', '''XLMRobertaOnnxConfig''', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = ['''XLMRobertaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = ['''XLMRobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaForCausalLM''', '''XLMRobertaForMaskedLM''', '''XLMRobertaForMultipleChoice''', '''XLMRobertaForQuestionAnswering''', '''XLMRobertaForSequenceClassification''', '''XLMRobertaForTokenClassification''', '''XLMRobertaModel''', '''XLMRobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ '''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMRobertaForCausalLM''', '''TFXLMRobertaForMaskedLM''', '''TFXLMRobertaForMultipleChoice''', '''TFXLMRobertaForQuestionAnswering''', '''TFXLMRobertaForSequenceClassification''', '''TFXLMRobertaForTokenClassification''', '''TFXLMRobertaModel''', '''TFXLMRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ '''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxXLMRobertaForMaskedLM''', '''FlaxXLMRobertaForCausalLM''', '''FlaxXLMRobertaForMultipleChoice''', '''FlaxXLMRobertaForQuestionAnswering''', '''FlaxXLMRobertaForSequenceClassification''', '''FlaxXLMRobertaForTokenClassification''', '''FlaxXLMRobertaModel''', '''FlaxXLMRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
323
1
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 snake_case__ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = XLMTokenizer _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Union[str, Any] ) ->Union[str, Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : str = [ '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>', ] snake_case__ : Any = dict(zip(A_, range(len(A_ ) ) ) ) snake_case__ : Optional[int] = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] snake_case__ : Tuple = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file'] ) snake_case__ : Union[str, Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file, 'w' ) as fp: fp.write(json.dumps(A_ ) ) with open(self.merges_file, 'w' ) as fp: fp.write('\n'.join(A_ ) ) def lowercase_ ( self : int, _snake_case : Any ) ->Dict: snake_case__ : Optional[Any] = 'lower newer' snake_case__ : Union[str, Any] = 'lower newer' return input_text, output_text def lowercase_ ( self : int ) ->List[str]: snake_case__ : Tuple = XLMTokenizer(self.vocab_file, self.merges_file ) snake_case__ : List[Any] = 'lower' snake_case__ : List[Any] = ['low', 'er</w>'] snake_case__ : List[Any] = tokenizer.tokenize(A_ ) self.assertListEqual(A_, A_ ) snake_case__ : List[Any] = tokens + ['<unk>'] snake_case__ : Union[str, Any] = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ), A_ ) @slow def lowercase_ ( self : Dict ) ->Optional[Any]: snake_case__ : Tuple = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) snake_case__ : Tuple = tokenizer.encode('sequence builders', add_special_tokens=A_ ) snake_case__ : str = tokenizer.encode('multi-sequence build', add_special_tokens=A_ ) snake_case__ : Tuple = tokenizer.build_inputs_with_special_tokens(A_ ) snake_case__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(A_, A_ ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
277
import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase ( _SCREAMING_SNAKE_CASE ): def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A_ , 'embed_dim' ) ) self.parent.assertTrue(hasattr(A_ , 'num_heads' ) ) class lowercase : def __init__( self , A_ , A_=13 , A_=64 , A_=3 , A_=[16, 48, 96] , A_=[1, 3, 6] , A_=[1, 2, 10] , A_=[7, 3, 3] , A_=[4, 2, 2] , A_=[2, 1, 1] , A_=[2, 2, 2] , A_=[False, False, True] , A_=[0.0, 0.0, 0.0] , A_=0.02 , A_=1e-12 , A_=True , A_=True , A_=2 , ) -> int: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_sizes UpperCamelCase = patch_stride UpperCamelCase = patch_padding UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = num_labels UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = num_heads UpperCamelCase = stride_kv UpperCamelCase = depth UpperCamelCase = cls_token UpperCamelCase = attention_drop_rate UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , A_ , A_ , A_ ) -> Any: """simple docstring""" UpperCamelCase = CvtModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase = model(A_ ) UpperCamelCase = (self.image_size, self.image_size) UpperCamelCase , UpperCamelCase = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCamelCase = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCamelCase = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCamelCase ( self , A_ , A_ , A_ ) -> Tuple: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = CvtForImageClassification(A_ ) model.to(A_ ) model.eval() UpperCamelCase = model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): __lowercase : List[str] = (CvtModel, CvtForImageClassification) if is_torch_available() else () __lowercase : Tuple = ( {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification} if is_torch_available() else {} ) __lowercase : Tuple = False __lowercase : Union[str, Any] = False __lowercase : Optional[Any] = False __lowercase : List[str] = False __lowercase : Dict = False def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = CvtModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def __UpperCamelCase ( self ) -> str: """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 __UpperCamelCase ( self ) -> Any: """simple docstring""" return @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" pass def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(A_ ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , A_ ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" def check_hidden_states_output(A_ , A_ , A_ ): UpperCamelCase = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(A_ , A_ ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = len(self.model_tester.depth ) self.assertEqual(len(A_ ) , A_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(A_ , A_ , A_ ) def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCamelCase ( self ) -> Dict: """simple docstring""" pass @slow def __UpperCamelCase ( self ) -> Dict: """simple docstring""" for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = CvtModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def A ( ) -> Tuple: '''simple docstring''' UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(A_ ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**A_ ) # verify the logits UpperCamelCase = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , A_ ) UpperCamelCase = torch.tensor([0.9285, 0.9015, -0.3150] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1e-4 ) )
222
0
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): A : List[str] = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) A : Union[str, Any] = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } A : Any = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Any = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Dict = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Extra Ignored Subsection''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], } ], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } A : Dict = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Any = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) A : int = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Union[str, Any] = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) A : int = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : List[str] = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' A : Optional[int] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : List[Any] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).''' A : int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' A : Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' A : Union[str, Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' A : List[str] = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' A : Union[str, Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' A : Optional[Any] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' A : str = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Any = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' A : Tuple = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' A : Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.''' A : Union[str, Any] = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.''' A : Union[str, Any] = '''''' A : str = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' A : List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' A : Optional[Any] = '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.''' @pytest.mark.parametrize( 'readme_md, expected_dict' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Optional[int] ,lowerCamelCase : Any ): assert ReadMe.from_string(lowerCamelCase ,lowerCamelCase ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Dict ,lowerCamelCase : Optional[Any] ): with pytest.raises(lowerCamelCase ,match=re.escape(expected_error.format(path='root' ) ) ): _A : List[Any] = ReadMe.from_string(lowerCamelCase ,lowerCamelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Optional[int] ,lowerCamelCase : Optional[int] ): with pytest.raises(lowerCamelCase ,match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(lowerCamelCase ,lowerCamelCase ) @pytest.mark.parametrize( 'readme_md,' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Tuple ): ReadMe.from_string(lowerCamelCase ,lowerCamelCase ,suppress_parsing_errors=lowerCamelCase ) @pytest.mark.parametrize( 'readme_md, expected_dict' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Tuple ,lowerCamelCase : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: _A : Optional[int] = Path(lowerCamelCase ) / 'README.md' with open(lowerCamelCase ,'w+' ) as readme_file: readme_file.write(lowerCamelCase ) _A : Union[str, Any] = ReadMe.from_readme(lowerCamelCase ,lowerCamelCase ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def lowerCAmelCase__ ( lowerCamelCase : List[Any] ,lowerCamelCase : List[str] ): with tempfile.TemporaryDirectory() as tmp_dir: _A : Dict = Path(lowerCamelCase ) / 'README.md' with open(lowerCamelCase ,'w+' ) as readme_file: readme_file.write(lowerCamelCase ) _A : Dict = expected_error.format(path=lowerCamelCase ) with pytest.raises(lowerCamelCase ,match=re.escape(lowerCamelCase ) ): _A : Dict = ReadMe.from_readme(lowerCamelCase ,lowerCamelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def lowerCAmelCase__ ( lowerCamelCase : Union[str, Any] ,lowerCamelCase : str ): with tempfile.TemporaryDirectory() as tmp_dir: _A : List[str] = Path(lowerCamelCase ) / 'README.md' with open(lowerCamelCase ,'w+' ) as readme_file: readme_file.write(lowerCamelCase ) _A : Any = expected_error.format(path=lowerCamelCase ) with pytest.raises(lowerCamelCase ,match=re.escape(lowerCamelCase ) ): ReadMe.from_readme(lowerCamelCase ,lowerCamelCase ) @pytest.mark.parametrize( 'readme_md,' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def lowerCAmelCase__ ( lowerCamelCase : str ): with tempfile.TemporaryDirectory() as tmp_dir: _A : Optional[int] = Path(lowerCamelCase ) / 'README.md' with open(lowerCamelCase ,'w+' ) as readme_file: readme_file.write(lowerCamelCase ) ReadMe.from_readme(lowerCamelCase ,lowerCamelCase ,suppress_parsing_errors=lowerCamelCase )
227
'''simple docstring''' def lowerCAmelCase__ ( lowerCamelCase : int ,lowerCamelCase : list[int] ,lowerCamelCase : int ): def count_of_possible_combinations(lowerCamelCase : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(lowerCamelCase ) def lowerCAmelCase__ ( lowerCamelCase : int ,lowerCamelCase : list[int] ,lowerCamelCase : int ): def count_of_possible_combinations_with_dp_array( lowerCamelCase : int ,lowerCamelCase : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] _A : Optional[Any] = sum( count_of_possible_combinations_with_dp_array(target - item ,lowerCamelCase ) for item in array ) _A : List[str] = answer return answer _A : Optional[int] = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(lowerCamelCase ,lowerCamelCase ) def lowerCAmelCase__ ( lowerCamelCase : int ,lowerCamelCase : list[int] ,lowerCamelCase : int ): _A : Dict = [0] * (target + 1) _A : List[str] = 1 for i in range(1 ,target + 1 ): for j in range(lowerCamelCase ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() A : Dict = 3 A : Union[str, Any] = 5 A : Union[str, Any] = [1, 2, 5] print(combination_sum_iv(n, array, target))
227
1
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : Union[str, Any] = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class lowerCamelCase__ ( __lowercase): '''simple docstring''' _A = 'owlvit_text_model' def __init__( self :Optional[Any] , a :List[str]=4_9_4_0_8 , a :Any=5_1_2 , a :int=2_0_4_8 , a :Tuple=1_2 , a :List[str]=8 , a :Optional[int]=1_6 , a :Optional[Any]="quick_gelu" , a :str=1E-5 , a :Optional[Any]=0.0 , a :Optional[int]=0.02 , a :Any=1.0 , a :Optional[Any]=0 , a :int=4_9_4_0_6 , a :Union[str, Any]=4_9_4_0_7 , **a :List[str] , ) -> Union[str, Any]: super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __UpperCamelCase : Tuple = vocab_size __UpperCamelCase : int = hidden_size __UpperCamelCase : Optional[int] = intermediate_size __UpperCamelCase : Dict = num_hidden_layers __UpperCamelCase : Tuple = num_attention_heads __UpperCamelCase : Optional[int] = max_position_embeddings __UpperCamelCase : str = hidden_act __UpperCamelCase : Union[str, Any] = layer_norm_eps __UpperCamelCase : Union[str, Any] = attention_dropout __UpperCamelCase : Tuple = initializer_range __UpperCamelCase : Any = initializer_factor @classmethod def _lowerCamelCase ( cls :int , a :Union[str, os.PathLike] , **a :Tuple ) -> "PretrainedConfig": cls._set_token_in_kwargs(a ) __UpperCamelCase , __UpperCamelCase : Tuple = cls.get_config_dict(a , **a ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __UpperCamelCase : List[Any] = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a , **a ) class lowerCamelCase__ ( __lowercase): '''simple docstring''' _A = 'owlvit_vision_model' def __init__( self :List[Any] , a :Optional[Any]=7_6_8 , a :Dict=3_0_7_2 , a :Dict=1_2 , a :List[Any]=1_2 , a :Any=3 , a :List[Any]=7_6_8 , a :Optional[Any]=3_2 , a :Dict="quick_gelu" , a :Union[str, Any]=1E-5 , a :str=0.0 , a :Optional[Any]=0.02 , a :int=1.0 , **a :List[str] , ) -> Dict: super().__init__(**a ) __UpperCamelCase : int = hidden_size __UpperCamelCase : Optional[int] = intermediate_size __UpperCamelCase : str = num_hidden_layers __UpperCamelCase : Tuple = num_attention_heads __UpperCamelCase : Optional[int] = num_channels __UpperCamelCase : str = image_size __UpperCamelCase : Any = patch_size __UpperCamelCase : List[Any] = hidden_act __UpperCamelCase : Optional[int] = layer_norm_eps __UpperCamelCase : Optional[Any] = attention_dropout __UpperCamelCase : Optional[int] = initializer_range __UpperCamelCase : Optional[Any] = initializer_factor @classmethod def _lowerCamelCase ( cls :List[str] , a :Union[str, os.PathLike] , **a :Optional[int] ) -> "PretrainedConfig": cls._set_token_in_kwargs(a ) __UpperCamelCase , __UpperCamelCase : Dict = cls.get_config_dict(a , **a ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __UpperCamelCase : List[Any] = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a , **a ) class lowerCamelCase__ ( __lowercase): '''simple docstring''' _A = 'owlvit' _A = True def __init__( self :List[Any] , a :Union[str, Any]=None , a :Optional[int]=None , a :Optional[int]=5_1_2 , a :Optional[int]=2.6592 , a :int=True , **a :Tuple , ) -> int: super().__init__(**a ) if text_config is None: __UpperCamelCase : int = {} logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." ) if vision_config is None: __UpperCamelCase : str = {} logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." ) __UpperCamelCase : str = OwlViTTextConfig(**a ) __UpperCamelCase : Dict = OwlViTVisionConfig(**a ) __UpperCamelCase : Tuple = projection_dim __UpperCamelCase : Optional[int] = logit_scale_init_value __UpperCamelCase : Union[str, Any] = return_dict __UpperCamelCase : List[str] = 1.0 @classmethod def _lowerCamelCase ( cls :str , a :Union[str, os.PathLike] , **a :Optional[Any] ) -> "PretrainedConfig": cls._set_token_in_kwargs(a ) __UpperCamelCase , __UpperCamelCase : Optional[int] = cls.get_config_dict(a , **a ) if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a , **a ) @classmethod def _lowerCamelCase ( cls :int , a :Dict , a :Dict , **a :Dict ) -> List[Any]: __UpperCamelCase : Optional[int] = {} __UpperCamelCase : str = text_config __UpperCamelCase : Optional[Any] = vision_config return cls.from_dict(a , **a ) def _lowerCamelCase ( self :str ) -> Tuple: __UpperCamelCase : Tuple = copy.deepcopy(self.__dict__ ) __UpperCamelCase : Optional[Any] = self.text_config.to_dict() __UpperCamelCase : Optional[int] = self.vision_config.to_dict() __UpperCamelCase : List[str] = self.__class__.model_type return output class lowerCamelCase__ ( __lowercase): '''simple docstring''' @property def _lowerCamelCase ( self :Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("attention_mask", {0: "batch", 1: "sequence"}), ] ) @property def _lowerCamelCase ( self :List[str] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("logits_per_image", {0: "batch"}), ("logits_per_text", {0: "batch"}), ("text_embeds", {0: "batch"}), ("image_embeds", {0: "batch"}), ] ) @property def _lowerCamelCase ( self :int ) -> float: return 1E-4 def _lowerCamelCase ( self :Optional[Any] , a :"ProcessorMixin" , a :int = -1 , a :int = -1 , a :Optional["TensorType"] = None , ) -> Mapping[str, Any]: __UpperCamelCase : Tuple = super().generate_dummy_inputs( processor.tokenizer , batch_size=a , seq_length=a , framework=a ) __UpperCamelCase : Dict = super().generate_dummy_inputs( processor.image_processor , batch_size=a , framework=a ) return {**text_input_dict, **image_input_dict} @property def _lowerCamelCase ( self :List[Any] ) -> int: return 1_4
232
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path lowercase : Optional[int] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) lowercase : Optional[Any] = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} lowercase : str = 'zero2' lowercase : Optional[int] = 'zero3' lowercase : Optional[Any] = [ZEROa, ZEROa] def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[str]) -> int: '''simple docstring''' __UpperCamelCase : Union[str, Any] = parameterized.to_safe_name("_".join(str(_lowerCamelCase) for x in param.args)) return F'{func.__name__}_{param_based_name}' # Cartesian-product of zero stages with models to test lowercase : List[str] = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class lowerCamelCase__ ( __lowercase): '''simple docstring''' @parameterized.expand(a , name_func=a ) def _lowerCamelCase ( self :Dict , a :Optional[Any] , a :str ) -> Optional[int]: self.run_and_check( stage=a , model=a , distributed=a , fpaa=a , ) @require_torch_multi_gpu @parameterized.expand(a , name_func=a ) def _lowerCamelCase ( self :List[str] , a :str , a :str ) -> List[Any]: self.run_and_check( stage=a , model=a , distributed=a , fpaa=a , ) @parameterized.expand(a , name_func=a ) def _lowerCamelCase ( self :List[Any] , a :List[str] , a :int ) -> Optional[int]: self.run_and_check( stage=a , model=a , distributed=a , fpaa=a , ) @require_torch_multi_gpu @parameterized.expand(a , name_func=a ) def _lowerCamelCase ( self :List[str] , a :List[Any] , a :Dict ) -> int: self.run_and_check( stage=a , model=a , distributed=a , fpaa=a , ) def _lowerCamelCase ( self :Any , a :List[str] ) -> Optional[Any]: # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def _lowerCamelCase ( self :Optional[Any] , a :str , a :str , a :int = 1_0 , a :bool = True , a :bool = True , a :bool = True , ) -> Any: __UpperCamelCase : Optional[Any] = models[model] __UpperCamelCase : List[Any] = self.run_trainer( stage=a , model_name=a , eval_steps=a , num_train_epochs=1 , distributed=a , fpaa=a , ) self.do_checks(a ) return output_dir def _lowerCamelCase ( self :List[str] , a :str , a :str , a :int = 1_0 , a :int = 1 , a :bool = True , a :bool = True , ) -> Dict: __UpperCamelCase : int = self.get_auto_remove_tmp_dir("./xxx" , after=a ) __UpperCamelCase : int = f'\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(a )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n '.split() if fpaa: args.extend(["--fp16"] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files __UpperCamelCase : Dict = f'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split() __UpperCamelCase : int = [f'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'] __UpperCamelCase : Optional[Any] = self.get_launcher(a ) __UpperCamelCase : Optional[int] = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(a , env=self.get_env() ) return output_dir def _lowerCamelCase ( self :Any , a :List[Any]=False ) -> List[Any]: # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) __UpperCamelCase : List[Any] = min(2 , get_gpu_count() ) if distributed else 1 return f'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()
232
1
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig lowercase : List[str] = logging.get_logger(__name__) # General docstring lowercase : Optional[Any] = 'MobileNetV1Config' # Base docstring lowercase : List[Any] = 'google/mobilenet_v1_1.0_224' lowercase : Dict = [1, 1024, 7, 7] # Image classification docstring lowercase : Dict = 'google/mobilenet_v1_1.0_224' lowercase : Tuple = 'tabby, tabby cat' lowercase : List[Any] = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_ (_lowerCAmelCase : Optional[int] , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any=None ): __UpperCamelCase : Optional[Any] = {} if isinstance(a__ , a__ ): __UpperCamelCase : Tuple = model.mobilenet_va else: __UpperCamelCase : int = model __UpperCamelCase : Any = "MobilenetV1/Conv2d_0/" __UpperCamelCase : Any = backbone.conv_stem.convolution.weight __UpperCamelCase : Union[str, Any] = backbone.conv_stem.normalization.bias __UpperCamelCase : int = backbone.conv_stem.normalization.weight __UpperCamelCase : Tuple = backbone.conv_stem.normalization.running_mean __UpperCamelCase : Optional[Any] = backbone.conv_stem.normalization.running_var for i in range(13 ): __UpperCamelCase : str = i + 1 __UpperCamelCase : Optional[Any] = i * 2 __UpperCamelCase : str = backbone.layer[pt_index] __UpperCamelCase : List[Any] = F'''MobilenetV1/Conv2d_{tf_index}_depthwise/''' __UpperCamelCase : Dict = pointer.convolution.weight __UpperCamelCase : int = pointer.normalization.bias __UpperCamelCase : Dict = pointer.normalization.weight __UpperCamelCase : Tuple = pointer.normalization.running_mean __UpperCamelCase : Dict = pointer.normalization.running_var __UpperCamelCase : str = backbone.layer[pt_index + 1] __UpperCamelCase : Dict = F'''MobilenetV1/Conv2d_{tf_index}_pointwise/''' __UpperCamelCase : Optional[int] = pointer.convolution.weight __UpperCamelCase : Union[str, Any] = pointer.normalization.bias __UpperCamelCase : List[Any] = pointer.normalization.weight __UpperCamelCase : Tuple = pointer.normalization.running_mean __UpperCamelCase : Union[str, Any] = pointer.normalization.running_var if isinstance(a__ , a__ ): __UpperCamelCase : Optional[int] = "MobilenetV1/Logits/Conv2d_1c_1x1/" __UpperCamelCase : Optional[Any] = model.classifier.weight __UpperCamelCase : Tuple = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_ (_lowerCAmelCase : Dict , _lowerCAmelCase : List[str] , _lowerCAmelCase : str ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise # Load weights from TF model __UpperCamelCase : str = tf.train.list_variables(a__ ) __UpperCamelCase : Any = {} for name, shape in init_vars: logger.info(F'''Loading TF weight {name} with shape {shape}''' ) __UpperCamelCase : Optional[Any] = tf.train.load_variable(a__ , a__ ) __UpperCamelCase : int = array # Build TF to PyTorch weights loading map __UpperCamelCase : str = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F'''Importing {name}''' ) if name not in tf_weights: logger.info(F'''{name} not in tf pre-trained weights, skipping''' ) continue __UpperCamelCase : List[Any] = tf_weights[name] if "depthwise_weights" in name: logger.info("Transposing depthwise" ) __UpperCamelCase : Union[str, Any] = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info("Transposing" ) if len(pointer.shape ) == 2: # copying into linear layer __UpperCamelCase : Any = array.squeeze().transpose() else: __UpperCamelCase : Optional[Any] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched''' ) logger.info(F'''Initialize PyTorch weight {name} {array.shape}''' ) __UpperCamelCase : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + "/RMSProp" , a__ ) tf_weights.pop(name + "/RMSProp_1" , a__ ) tf_weights.pop(name + "/ExponentialMovingAverage" , a__ ) logger.info(F'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}''' ) return model def UpperCAmelCase_ (_lowerCAmelCase : Dict , _lowerCAmelCase : Tuple ): __UpperCamelCase , __UpperCamelCase : List[Any] = features.shape[-2:] __UpperCamelCase , __UpperCamelCase : List[str] = conv_layer.stride __UpperCamelCase , __UpperCamelCase : Union[str, Any] = conv_layer.kernel_size if in_height % stride_height == 0: __UpperCamelCase : List[Any] = max(kernel_height - stride_height , 0 ) else: __UpperCamelCase : List[Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __UpperCamelCase : Tuple = max(kernel_width - stride_width , 0 ) else: __UpperCamelCase : int = max(kernel_width - (in_width % stride_width) , 0 ) __UpperCamelCase : Dict = pad_along_width // 2 __UpperCamelCase : Any = pad_along_width - pad_left __UpperCamelCase : Union[str, Any] = pad_along_height // 2 __UpperCamelCase : int = pad_along_height - pad_top __UpperCamelCase : List[str] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , "constant" , 0.0 ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): """simple docstring""" def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 1 , __UpperCamelCase = 1 , __UpperCamelCase = False , __UpperCamelCase = True , __UpperCamelCase = True , ) -> None: '''simple docstring''' super().__init__() __UpperCamelCase : Any = config if in_channels % groups != 0: raise ValueError(f'''Input channels ({in_channels}) are not divisible by {groups} groups.''' ) if out_channels % groups != 0: raise ValueError(f'''Output channels ({out_channels}) are not divisible by {groups} groups.''' ) __UpperCamelCase : Optional[int] = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __UpperCamelCase : Optional[int] = nn.Convad( in_channels=_snake_case , out_channels=_snake_case , kernel_size=_snake_case , stride=_snake_case , padding=_snake_case , groups=_snake_case , bias=_snake_case , padding_mode="zeros" , ) if use_normalization: __UpperCamelCase : int = nn.BatchNormad( num_features=_snake_case , eps=config.layer_norm_eps , momentum=0.9997 , affine=_snake_case , track_running_stats=_snake_case , ) else: __UpperCamelCase : Union[str, Any] = None if use_activation: if isinstance(_snake_case , _snake_case ): __UpperCamelCase : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _snake_case ): __UpperCamelCase : Optional[Any] = ACTaFN[config.hidden_act] else: __UpperCamelCase : List[str] = config.hidden_act else: __UpperCamelCase : Tuple = None def __lowerCamelCase ( self , __UpperCamelCase ) -> torch.Tensor: '''simple docstring''' if self.config.tf_padding: __UpperCamelCase : Optional[Any] = apply_tf_padding(_snake_case , self.convolution ) __UpperCamelCase : Union[str, Any] = self.convolution(_snake_case ) if self.normalization is not None: __UpperCamelCase : Optional[Any] = self.normalization(_snake_case ) if self.activation is not None: __UpperCamelCase : Optional[Any] = self.activation(_snake_case ) return features class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" lowercase : Union[str, Any] = MobileNetVaConfig lowercase : Optional[int] = load_tf_weights_in_mobilenet_va lowercase : str = 'mobilenet_v1' lowercase : int = 'pixel_values' lowercase : List[Any] = False def __lowerCamelCase ( self , __UpperCamelCase ) -> None: '''simple docstring''' if isinstance(_snake_case , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_snake_case , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) lowercase : Dict = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): 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' lowercase : Tuple = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__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 MobileNetV1 model outputting raw hidden-states without any specific head on top.' , lowerCamelCase__ , ) class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" def __init__( self , __UpperCamelCase , __UpperCamelCase = True ) -> Dict: '''simple docstring''' super().__init__(_snake_case ) __UpperCamelCase : Union[str, Any] = config __UpperCamelCase : Tuple = 32 __UpperCamelCase : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) __UpperCamelCase : Optional[Any] = MobileNetVaConvLayer( _snake_case , in_channels=config.num_channels , out_channels=_snake_case , kernel_size=3 , stride=2 , ) __UpperCamelCase : Dict = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __UpperCamelCase : Optional[Any] = nn.ModuleList() for i in range(13 ): __UpperCamelCase : Any = out_channels if strides[i] == 2 or i == 0: depth *= 2 __UpperCamelCase : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _snake_case , in_channels=_snake_case , out_channels=_snake_case , kernel_size=3 , stride=strides[i] , groups=_snake_case , ) ) self.layer.append( MobileNetVaConvLayer( _snake_case , in_channels=_snake_case , out_channels=_snake_case , kernel_size=1 , ) ) __UpperCamelCase : List[Any] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCamelCase ( self , __UpperCamelCase ) -> int: '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(_snake_case ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_snake_case , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCamelCase ( self , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: '''simple docstring''' __UpperCamelCase : str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __UpperCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("You have to specify pixel_values" ) __UpperCamelCase : List[Any] = self.conv_stem(_snake_case ) __UpperCamelCase : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __UpperCamelCase : Union[str, Any] = layer_module(_snake_case ) if output_hidden_states: __UpperCamelCase : Dict = all_hidden_states + (hidden_states,) __UpperCamelCase : List[str] = hidden_states if self.pooler is not None: __UpperCamelCase : List[str] = torch.flatten(self.pooler(_snake_case ) , start_dim=1 ) else: __UpperCamelCase : Union[str, Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_snake_case , pooler_output=_snake_case , hidden_states=_snake_case , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCamelCase__ , ) class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" def __init__( self , __UpperCamelCase ) -> None: '''simple docstring''' super().__init__(_snake_case ) __UpperCamelCase : List[str] = config.num_labels __UpperCamelCase : List[Any] = MobileNetVaModel(_snake_case ) __UpperCamelCase : Tuple = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __UpperCamelCase : int = nn.Dropout(config.classifier_dropout_prob , inplace=_snake_case ) __UpperCamelCase : List[Any] = nn.Linear(_snake_case , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_snake_case ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_snake_case , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCamelCase ( self , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]: '''simple docstring''' __UpperCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __UpperCamelCase : Optional[Any] = self.mobilenet_va(_snake_case , output_hidden_states=_snake_case , return_dict=_snake_case ) __UpperCamelCase : Optional[Any] = outputs.pooler_output if return_dict else outputs[1] __UpperCamelCase : List[str] = self.classifier(self.dropout(_snake_case ) ) __UpperCamelCase : str = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __UpperCamelCase : Union[str, Any] = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __UpperCamelCase : Any = "single_label_classification" else: __UpperCamelCase : Union[str, Any] = "multi_label_classification" if self.config.problem_type == "regression": __UpperCamelCase : Optional[int] = MSELoss() if self.num_labels == 1: __UpperCamelCase : Tuple = loss_fct(logits.squeeze() , labels.squeeze() ) else: __UpperCamelCase : Union[str, Any] = loss_fct(_snake_case , _snake_case ) elif self.config.problem_type == "single_label_classification": __UpperCamelCase : List[str] = CrossEntropyLoss() __UpperCamelCase : Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __UpperCamelCase : Any = BCEWithLogitsLoss() __UpperCamelCase : List[Any] = loss_fct(_snake_case , _snake_case ) if not return_dict: __UpperCamelCase : Dict = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_snake_case , logits=_snake_case , hidden_states=outputs.hidden_states , )
361
from math import sqrt def UpperCAmelCase_ (_lowerCAmelCase : int = 1_00_00_00 ): __UpperCamelCase : int = 0 __UpperCamelCase : int = 0 __UpperCamelCase : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(_lowerCAmelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F"""{solution() = }""")
171
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __lowerCamelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' a_ : Dict = """big_bird""" def __init__( self : Dict , a_ : Union[str, Any]=5_03_58 , a_ : Dict=7_68 , a_ : Any=12 , a_ : List[Any]=12 , a_ : Optional[int]=30_72 , a_ : Union[str, Any]="gelu_new" , a_ : Any=0.1 , a_ : Optional[Any]=0.1 , a_ : Optional[int]=40_96 , a_ : List[Any]=2 , a_ : Any=0.02 , a_ : Tuple=1e-1_2 , a_ : Tuple=True , a_ : Optional[int]=0 , a_ : List[Any]=1 , a_ : Tuple=2 , a_ : Optional[int]=66 , a_ : int="block_sparse" , a_ : List[Any]=True , a_ : Dict=False , a_ : str=64 , a_ : str=3 , a_ : Union[str, Any]=None , **a_ : Any , ): super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , sep_token_id=a_ , **a_ , ) lowerCAmelCase_ : int = vocab_size lowerCAmelCase_ : Dict = max_position_embeddings lowerCAmelCase_ : Union[str, Any] = hidden_size lowerCAmelCase_ : Union[str, Any] = num_hidden_layers lowerCAmelCase_ : int = num_attention_heads lowerCAmelCase_ : List[Any] = intermediate_size lowerCAmelCase_ : Tuple = hidden_act lowerCAmelCase_ : List[str] = hidden_dropout_prob lowerCAmelCase_ : Optional[Any] = attention_probs_dropout_prob lowerCAmelCase_ : Tuple = initializer_range lowerCAmelCase_ : str = type_vocab_size lowerCAmelCase_ : int = layer_norm_eps lowerCAmelCase_ : Tuple = use_cache lowerCAmelCase_ : Any = rescale_embeddings lowerCAmelCase_ : Optional[int] = attention_type lowerCAmelCase_ : Tuple = use_bias lowerCAmelCase_ : Any = block_size lowerCAmelCase_ : Any = num_random_blocks lowerCAmelCase_ : List[str] = classifier_dropout class __lowerCamelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property def lowerCamelCase ( self : Tuple ): if self.task == "multiple-choice": lowerCAmelCase_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: lowerCAmelCase_ : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
241
def a__ ( __UpperCamelCase ): if not head: return True # split the list to two parts SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = head.next, head while fast and fast.next: SCREAMING_SNAKE_CASE_ = fast.next.next SCREAMING_SNAKE_CASE_ = slow.next SCREAMING_SNAKE_CASE_ = slow.next SCREAMING_SNAKE_CASE_ = None # Don't forget here! But forget still works! # reverse the second part SCREAMING_SNAKE_CASE_ = None while second: SCREAMING_SNAKE_CASE_ = second.next SCREAMING_SNAKE_CASE_ = node SCREAMING_SNAKE_CASE_ = second SCREAMING_SNAKE_CASE_ = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False SCREAMING_SNAKE_CASE_ = node.next SCREAMING_SNAKE_CASE_ = head.next return True def a__ ( __UpperCamelCase ): if not head or not head.next: return True # 1. Get the midpoint (slow) SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = head while fast and fast.next: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = fast.next.next, slow.next # 2. Push the second half into the stack SCREAMING_SNAKE_CASE_ = [slow.val] while slow.next: SCREAMING_SNAKE_CASE_ = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False SCREAMING_SNAKE_CASE_ = cur.next return True def a__ ( __UpperCamelCase ): if not head or not head.next: return True SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = 0 while head: if head.val in d: d[head.val].append(__UpperCamelCase ) else: SCREAMING_SNAKE_CASE_ = [pos] SCREAMING_SNAKE_CASE_ = head.next pos += 1 SCREAMING_SNAKE_CASE_ = pos - 1 SCREAMING_SNAKE_CASE_ = 0 for v in d.values(): if len(__UpperCamelCase ) % 2 != 0: middle += 1 else: SCREAMING_SNAKE_CASE_ = 0 for i in range(0 , len(__UpperCamelCase ) ): if v[i] + v[len(__UpperCamelCase ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
118
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL __A : List[str] = logging.get_logger(__name__) def __SCREAMING_SNAKE_CASE ( lowercase__ ): """simple docstring""" if isinstance(lowercase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowercase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowercase__ ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class __UpperCamelCase ( _A ): SCREAMING_SNAKE_CASE = ["pixel_values"] def __init__(self : str , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : PILImageResampling = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Union[int, float] = 1 / 2_5_5 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ): super().__init__(**__SCREAMING_SNAKE_CASE) A = size if size is not None else {"shortest_edge": 2_5_6} A = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE) A = crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4} A = get_size_dict(__SCREAMING_SNAKE_CASE , param_name="crop_size") A = do_resize A = size A = do_center_crop A = crop_size A = resample A = do_rescale A = rescale_factor A = offset A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ (self : Union[str, Any] , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Dict[str, int] , __SCREAMING_SNAKE_CASE : PILImageResampling = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Dict , ): A = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE) if "shortest_edge" in size: A = get_resize_output_image_size(__SCREAMING_SNAKE_CASE , size["shortest_edge"] , default_to_square=__SCREAMING_SNAKE_CASE) elif "height" in size and "width" in size: A = (size["height"], size["width"]) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""") return resize(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Tuple , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Dict[str, int] , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ): A = get_size_dict(__SCREAMING_SNAKE_CASE) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""") return center_crop(__SCREAMING_SNAKE_CASE , size=(size["height"], size["width"]) , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : List[Any] , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Union[int, float] , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Tuple , ): A = image.astype(np.floataa) if offset: A = image - (scale / 2) return rescale(__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Optional[int] , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : Union[float, List[float]] , __SCREAMING_SNAKE_CASE : Union[float, List[float]] , __SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **__SCREAMING_SNAKE_CASE : Dict , ): return normalize(__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : str , __SCREAMING_SNAKE_CASE : ImageInput , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : PILImageResampling = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : float = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True.") if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True.") if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True.") if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True.") # All transformations expect numpy arrays. A = to_numpy_array(__SCREAMING_SNAKE_CASE) if do_resize: A = self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE) if do_center_crop: A = self.center_crop(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE) if do_rescale: A = self.rescale(image=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , offset=__SCREAMING_SNAKE_CASE) if do_normalize: A = self.normalize(image=__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE) A = to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) return image def SCREAMING_SNAKE_CASE__ (self : Optional[Any] , __SCREAMING_SNAKE_CASE : ImageInput , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : PILImageResampling = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Dict[str, int] = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : float = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : bool = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[float, List[float]]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , __SCREAMING_SNAKE_CASE : ChannelDimension = ChannelDimension.FIRST , **__SCREAMING_SNAKE_CASE : List[Any] , ): A = do_resize if do_resize is not None else self.do_resize A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = offset if offset is not None else self.offset A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = size if size is not None else self.size A = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE) A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(__SCREAMING_SNAKE_CASE , param_name="crop_size") 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.") A = make_batched(__SCREAMING_SNAKE_CASE) A = [ [ self._preprocess_image( image=__SCREAMING_SNAKE_CASE , do_resize=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , do_center_crop=__SCREAMING_SNAKE_CASE , crop_size=__SCREAMING_SNAKE_CASE , do_rescale=__SCREAMING_SNAKE_CASE , rescale_factor=__SCREAMING_SNAKE_CASE , offset=__SCREAMING_SNAKE_CASE , do_normalize=__SCREAMING_SNAKE_CASE , image_mean=__SCREAMING_SNAKE_CASE , image_std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , ) for img in video ] for video in videos ] A = {"pixel_values": videos} return BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE)
57
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger __A : Union[str, Any] = get_logger(__name__) class __UpperCamelCase ( enum.Enum ): SCREAMING_SNAKE_CASE = "all_checks" SCREAMING_SNAKE_CASE = "basic_checks" SCREAMING_SNAKE_CASE = "no_checks" class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , lowercase__=None ): """simple docstring""" if expected_checksums is None: logger.info("Unable to verify checksums." ) return if len(set(lowercase__ ) - set(lowercase__ ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(lowercase__ ) - set(lowercase__ ) ) ) if len(set(lowercase__ ) - set(lowercase__ ) ) > 0: raise UnexpectedDownloadedFile(str(set(lowercase__ ) - set(lowercase__ ) ) ) A = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] A = " for " + verification_name if verification_name is not None else "" if len(lowercase__ ) > 0: raise NonMatchingChecksumError( F"""Checksums didn't match{for_verification_name}:\n""" F"""{bad_urls}\n""" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error" ) logger.info("All the checksums matched successfully" + for_verification_name ) class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass class __UpperCamelCase ( _A ): pass def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ ): """simple docstring""" if expected_splits is None: logger.info("Unable to verify splits sizes." ) return if len(set(lowercase__ ) - set(lowercase__ ) ) > 0: raise ExpectedMoreSplits(str(set(lowercase__ ) - set(lowercase__ ) ) ) if len(set(lowercase__ ) - set(lowercase__ ) ) > 0: raise UnexpectedSplits(str(set(lowercase__ ) - set(lowercase__ ) ) ) A = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(lowercase__ ) > 0: raise NonMatchingSplitsSizesError(str(lowercase__ ) ) logger.info("All the splits matched successfully." ) def __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ = True ): """simple docstring""" if record_checksum: A = shaaaa() with open(lowercase__ , "rb" ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B"" ): m.update(lowercase__ ) A = m.hexdigest() else: A = None return {"num_bytes": os.path.getsize(lowercase__ ), "checksum": checksum} def __SCREAMING_SNAKE_CASE ( lowercase__ ): """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
57
1
'''simple docstring''' # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class a__ ( UpperCAmelCase__ ): lowerCamelCase : torch.FloatTensor lowerCamelCase : Optional[torch.FloatTensor] =None def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__=0.9_9_9 , UpperCamelCase__="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCamelCase__ ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCamelCase__ ): return math.exp(t * -1_2.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) __lowerCamelCase = [] for i in range(UpperCamelCase__ ): __lowerCamelCase = i / num_diffusion_timesteps __lowerCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCamelCase__ ) / alpha_bar_fn(UpperCamelCase__ ) , UpperCamelCase__ ) ) return torch.tensor(UpperCamelCase__ , dtype=torch.floataa ) class a__ ( UpperCAmelCase__ , UpperCAmelCase__ ): lowerCamelCase : List[Any] =1 @register_to_config def __init__( self : Union[str, Any] , a : int = 10_00 , a : float = 0.00_01 , a : float = 0.02 , a : str = "linear" , a : Optional[Union[np.ndarray, List[float]]] = None , a : bool = True , a : bool = True , a : int = 0 , a : str = "epsilon" , a : float = 1.0 , **a : List[str] , ): """simple docstring""" if kwargs.get('''set_alpha_to_one''' , a ) is not None: __lowerCamelCase = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''' , '''1.0.0''' , a , standard_warn=a ) __lowerCamelCase = kwargs['''set_alpha_to_one'''] if trained_betas is not None: __lowerCamelCase = torch.tensor(a , dtype=torch.floataa ) elif beta_schedule == "linear": __lowerCamelCase = torch.linspace(a , a , a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __lowerCamelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __lowerCamelCase = betas_for_alpha_bar(a ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) __lowerCamelCase = 1.0 - self.betas __lowerCamelCase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. __lowerCamelCase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution __lowerCamelCase = 1.0 # setable values __lowerCamelCase = None __lowerCamelCase = torch.from_numpy(np.arange(0 , a ).copy().astype(np.intaa ) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : torch.FloatTensor , a : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE__ ( self : Dict , a : int , a : Union[str, torch.device] = None ): """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:""" f""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle""" f""" maximal {self.config.num_train_timesteps} timesteps.""" ) __lowerCamelCase = num_inference_steps __lowerCamelCase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __lowerCamelCase = (np.arange(0 , a ) * step_ratio).round().copy().astype(np.intaa ) __lowerCamelCase = torch.from_numpy(a ).to(a ) self.timesteps += self.config.steps_offset def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : torch.FloatTensor , a : int , a : torch.FloatTensor , a : float = 0.0 , a : bool = False , a : Optional[torch.FloatTensor] = None , a : bool = True , ): """simple docstring""" __lowerCamelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process __lowerCamelCase = self.alphas_cumprod[timestep] __lowerCamelCase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) __lowerCamelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": __lowerCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 __lowerCamelCase = model_output elif self.config.prediction_type == "sample": __lowerCamelCase = model_output __lowerCamelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": __lowerCamelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output __lowerCamelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or""" ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: __lowerCamelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=a , pred_original_sample=a ) def __len__( self : str ): """simple docstring""" return self.config.num_train_timesteps
67
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' A = BlenderbotSmallTokenizer A = False def a_ (self ) -> List[str]: super().setUp() __UpperCamelCase : Optional[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] __UpperCamelCase : int = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) ) __UpperCamelCase : Any = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] __UpperCamelCase : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} __UpperCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(_UpperCAmelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(_UpperCAmelCase ) ) def a_ (self , **_UpperCAmelCase ) -> Dict: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def a_ (self , _UpperCAmelCase ) -> str: __UpperCamelCase : List[Any] = "adapt act apte" __UpperCamelCase : Dict = "adapt act apte" return input_text, output_text def a_ (self ) -> int: __UpperCamelCase : List[str] = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase : str = "adapt act apte" __UpperCamelCase : List[str] = ["adapt", "act", "ap@@", "te"] __UpperCamelCase : Union[str, Any] = tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) __UpperCamelCase : Dict = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] __UpperCamelCase : Any = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , _UpperCAmelCase ) def a_ (self ) -> int: __UpperCamelCase : Optional[int] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1_3_8_4] __UpperCamelCase : Dict = "I am a small frog." __UpperCamelCase : Any = tok([src_text] , padding=_UpperCAmelCase , truncation=_UpperCAmelCase )["input_ids"] __UpperCamelCase : Optional[Any] = tok.batch_decode(_UpperCAmelCase , skip_special_tokens=_UpperCAmelCase , clean_up_tokenization_spaces=_UpperCAmelCase )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def a_ (self ) -> List[Any]: __UpperCamelCase : Dict = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) __UpperCamelCase : Tuple = "I am a small frog ." __UpperCamelCase : List[str] = "." __UpperCamelCase : Any = tok(_UpperCAmelCase )["input_ids"] __UpperCamelCase : Optional[Any] = tok(_UpperCAmelCase )["input_ids"] assert encoded[-1] == encoded_dot[0]
298
0
"""simple docstring""" import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __UpperCAmelCase ( lowercase=None ,lowercase=None ): """simple docstring""" return field(default_factory=lambda: default ,metadata=lowercase ) @dataclass class a : _snake_case : str = field( metadata={'help': 'The csv file to plot.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Whether to plot along batch size or sequence length. Defaults to sequence length.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Whether the csv file has time results or memory results. Defaults to memory results.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Disable logarithmic scale when plotting'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={ 'help': 'Whether the csv file has training results or inference results. Defaults to inference results.' } , ) _snake_case : Optional[str] = field( default=lowerCAmelCase_ , metadata={'help': 'Filename under which the plot will be saved. If unused no plot is saved.'} , ) _snake_case : Optional[List[str]] = list_field( default=lowerCAmelCase_ , metadata={'help': 'List of model names that are used instead of the ones in the csv file.'} ) def __UpperCAmelCase ( lowercase ): """simple docstring""" try: int(lowercase ) return True except ValueError: return False def __UpperCAmelCase ( lowercase ): """simple docstring""" try: float(lowercase ) return True except ValueError: return False class a : def __init__( self : int , __lowerCAmelCase : Union[str, Any] ): _UpperCAmelCase = args _UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline="""""" ) as csv_file: _UpperCAmelCase = csv.DictReader(__lowerCAmelCase ) for row in reader: _UpperCAmelCase = row["""model"""] self.result_dict[model_name]["bsz"].append(int(row["""batch_size"""] ) ) self.result_dict[model_name]["seq_len"].append(int(row["""sequence_length"""] ) ) if can_convert_to_int(row["""result"""] ): # value is not None _UpperCAmelCase = int(row["""result"""] ) elif can_convert_to_float(row["""result"""] ): # value is not None _UpperCAmelCase = float(row["""result"""] ) def lowerCAmelCase_ ( self : Optional[Any] ): _UpperCAmelCase , _UpperCAmelCase = plt.subplots() _UpperCAmelCase = """Time usage""" if self.args.is_time else """Memory usage""" _UpperCAmelCase = title_str + """ for training""" if self.args.is_train else title_str + """ for inference""" if not self.args.no_log_scale: # set logarithm scales ax.set_xscale("""log""" ) ax.set_yscale("""log""" ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): _UpperCAmelCase = sorted(set(self.result_dict[model_name]["""bsz"""] ) ) _UpperCAmelCase = sorted(set(self.result_dict[model_name]["""seq_len"""] ) ) _UpperCAmelCase = self.result_dict[model_name]["""result"""] ((_UpperCAmelCase) , (_UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) _UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: _UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=__lowerCAmelCase , ) else: _UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((_UpperCAmelCase) , (_UpperCAmelCase)) = ( ("""batch_size""", """len""") if self.args.plot_along_batch else ("""in #tokens""", """bsz""") ) _UpperCAmelCase = np.asarray(__lowerCAmelCase , __lowerCAmelCase )[: len(__lowerCAmelCase )] plt.scatter( __lowerCAmelCase , __lowerCAmelCase , label=f'''{label_model_name} - {inner_loop_label}: {inner_loop_value}''' ) plt.plot(__lowerCAmelCase , __lowerCAmelCase , """--""" ) title_str += f''' {label_model_name} vs.''' _UpperCAmelCase = title_str[:-4] _UpperCAmelCase = """Time in s""" if self.args.is_time else """Memory in MB""" # plot plt.title(__lowerCAmelCase ) plt.xlabel(__lowerCAmelCase ) plt.ylabel(__lowerCAmelCase ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = HfArgumentParser(lowercase ) _UpperCAmelCase = parser.parse_args_into_dataclasses()[0] _UpperCAmelCase = Plot(args=lowercase ) plot.plot() if __name__ == "__main__": main()
30
"""simple docstring""" 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() UpperCAmelCase__ = logging.get_logger(__name__) def __UpperCAmelCase ( lowercase ,lowercase=False ): """simple docstring""" _UpperCAmelCase = [] # 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" _UpperCAmelCase = [(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 __UpperCAmelCase ( lowercase ,lowercase ,lowercase=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _UpperCAmelCase = """""" else: _UpperCAmelCase = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCAmelCase = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) _UpperCAmelCase = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _UpperCAmelCase = in_proj_weight[ : config.hidden_size, : ] _UpperCAmelCase = in_proj_bias[: config.hidden_size] _UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCAmelCase = in_proj_weight[ -config.hidden_size :, : ] _UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(lowercase ,lowercase ) def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = dct.pop(lowercase ) _UpperCAmelCase = val def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" _UpperCAmelCase = Image.open(requests.get(lowercase ,stream=lowercase ).raw ) return im @torch.no_grad() def __UpperCAmelCase ( lowercase ,lowercase ,lowercase=False ): """simple docstring""" _UpperCAmelCase = BitConfig( global_padding="""same""" ,layer_type="""bottleneck""" ,depths=(3, 4, 9) ,out_features=["""stage3"""] ,embedding_dynamic_padding=lowercase ,) _UpperCAmelCase = ViTHybridConfig(backbone_config=lowercase ,image_size=3_84 ,num_labels=10_00 ) _UpperCAmelCase = False # load original model from timm _UpperCAmelCase = timm.create_model(lowercase ,pretrained=lowercase ) timm_model.eval() # load state_dict of original model, remove and rename some keys _UpperCAmelCase = timm_model.state_dict() if base_model: remove_classification_head_(lowercase ) _UpperCAmelCase = create_rename_keys(lowercase ,lowercase ) for src, dest in rename_keys: rename_key(lowercase ,lowercase ,lowercase ) read_in_q_k_v(lowercase ,lowercase ,lowercase ) _UpperCAmelCase = """huggingface/label-files""" _UpperCAmelCase = """imagenet-1k-id2label.json""" _UpperCAmelCase = json.load(open(hf_hub_download(lowercase ,lowercase ,repo_type="""dataset""" ) ,"""r""" ) ) _UpperCAmelCase = {int(lowercase ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": _UpperCAmelCase = ViTHybridModel(lowercase ).eval() else: _UpperCAmelCase = ViTHybridForImageClassification(lowercase ).eval() model.load_state_dict(lowercase ) # create image processor _UpperCAmelCase = create_transform(**resolve_data_config({} ,model=lowercase ) ) _UpperCAmelCase = transform.transforms _UpperCAmelCase = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } _UpperCAmelCase = ViTHybridImageProcessor( do_resize=lowercase ,size={"""shortest_edge""": timm_transforms[0].size} ,resample=pillow_resamplings[timm_transforms[0].interpolation.value] ,do_center_crop=lowercase ,crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} ,do_normalize=lowercase ,image_mean=timm_transforms[-1].mean.tolist() ,image_std=timm_transforms[-1].std.tolist() ,) _UpperCAmelCase = prepare_img() _UpperCAmelCase = transform(lowercase ).unsqueeze(0 ) _UpperCAmelCase = processor(lowercase ,return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(lowercase ,lowercase ) # verify logits with torch.no_grad(): _UpperCAmelCase = model(lowercase ) _UpperCAmelCase = outputs.logits print("""Predicted class:""" ,logits.argmax(-1 ).item() ) if base_model: _UpperCAmelCase = timm_model.forward_features(lowercase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowercase ,outputs.pooler_output ,atol=1E-3 ) else: _UpperCAmelCase = timm_model(lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase ,outputs.logits ,atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(lowercase ).mkdir(exist_ok=lowercase ) print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowercase ) 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__": UpperCAmelCase__ = 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.""" ) UpperCAmelCase__ = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
30
1
from __future__ import annotations from functools import lru_cache from math import ceil a : int = 100 a : Union[str, Any] = set(range(3, NUM_PRIMES, 2)) primes.add(2) a : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def lowerCamelCase__ ( __lowerCamelCase : int ): if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} __UpperCAmelCase : set[int] = set() __UpperCAmelCase : int __UpperCAmelCase : int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def lowerCamelCase__ ( __lowerCamelCase : int = 5000 ): for number_to_partition in range(1 , __lowerCamelCase ): if len(partition(__lowerCamelCase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
114
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a : List[str] = "src/diffusers" a : str = "." # This is to make sure the diffusers module imported is the one in the repo. a : Tuple = importlib.util.spec_from_file_location( "diffusers", os.path.join(DIFFUSERS_PATH, "__init__.py"), submodule_search_locations=[DIFFUSERS_PATH], ) a : List[str] = spec.loader.load_module() def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): return line.startswith(__lowerCamelCase ) or len(__lowerCamelCase ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""" , __lowerCamelCase ) is not None def lowerCamelCase__ ( __lowerCamelCase : Any ): __UpperCAmelCase : Optional[int] = object_name.split(""".""" ) __UpperCAmelCase : List[Any] = 0 # First let's find the module where our object lives. __UpperCAmelCase : Optional[Any] = parts[i] while i < len(__lowerCamelCase ) and not os.path.isfile(os.path.join(__lowerCamelCase , f"""{module}.py""" ) ): i += 1 if i < len(__lowerCamelCase ): __UpperCAmelCase : List[str] = os.path.join(__lowerCamelCase , parts[i] ) if i >= len(__lowerCamelCase ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(__lowerCamelCase , f"""{module}.py""" ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: __UpperCAmelCase : Optional[Any] = f.readlines() # Now let's find the class / func in the code! __UpperCAmelCase : List[str] = """""" __UpperCAmelCase : int = 0 for name in parts[i + 1 :]: while ( line_index < len(__lowerCamelCase ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__lowerCamelCase ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __UpperCAmelCase : List[str] = line_index while line_index < len(__lowerCamelCase ) and _should_continue(lines[line_index] , __lowerCamelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __UpperCAmelCase : Dict = lines[start_index:line_index] return "".join(__lowerCamelCase ) a : Any = re.compile(r"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") a : Optional[int] = re.compile(r"^\s*(\S+)->(\S+)(\s+.*|$)") a : Dict = re.compile(r"<FILL\s+[^>]*>") def lowerCamelCase__ ( __lowerCamelCase : List[Any] ): __UpperCAmelCase : Optional[Any] = code.split("""\n""" ) __UpperCAmelCase : str = 0 while idx < len(__lowerCamelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__lowerCamelCase ): return re.search(R"""^(\s*)\S""" , lines[idx] ).groups()[0] return "" def lowerCamelCase__ ( __lowerCamelCase : List[str] ): __UpperCAmelCase : Tuple = len(get_indent(__lowerCamelCase ) ) > 0 if has_indent: __UpperCAmelCase : Optional[Any] = f"""class Bla:\n{code}""" __UpperCAmelCase : Dict = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=__lowerCamelCase ) __UpperCAmelCase : Dict = black.format_str(__lowerCamelCase , mode=__lowerCamelCase ) __UpperCAmelCase , __UpperCAmelCase : Any = style_docstrings_in_code(__lowerCamelCase ) return result[len("""class Bla:\n""" ) :] if has_indent else result def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any]=False ): with open(__lowerCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: __UpperCAmelCase : Optional[Any] = f.readlines() __UpperCAmelCase : Optional[int] = [] __UpperCAmelCase : str = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__lowerCamelCase ): __UpperCAmelCase : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = search.groups() __UpperCAmelCase : Any = find_code_in_diffusers(__lowerCamelCase ) __UpperCAmelCase : Optional[int] = get_indent(__lowerCamelCase ) __UpperCAmelCase : Tuple = line_index + 1 if indent == theoretical_indent else line_index + 2 __UpperCAmelCase : Any = theoretical_indent __UpperCAmelCase : Any = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __UpperCAmelCase : int = True while line_index < len(__lowerCamelCase ) and should_continue: line_index += 1 if line_index >= len(__lowerCamelCase ): break __UpperCAmelCase : List[Any] = lines[line_index] __UpperCAmelCase : str = _should_continue(__lowerCamelCase , __lowerCamelCase ) and re.search(f"""^{indent}# End copy""" , __lowerCamelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __UpperCAmelCase : Optional[int] = lines[start_index:line_index] __UpperCAmelCase : int = """""".join(__lowerCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies __UpperCAmelCase : Tuple = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(__lowerCamelCase ) is None] __UpperCAmelCase : List[Any] = """\n""".join(__lowerCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__lowerCamelCase ) > 0: __UpperCAmelCase : List[str] = replace_pattern.replace("""with""" , """""" ).split(""",""" ) __UpperCAmelCase : Any = [_re_replace_pattern.search(__lowerCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = pattern.groups() __UpperCAmelCase : List[str] = re.sub(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if option.strip() == "all-casing": __UpperCAmelCase : List[Any] = re.sub(obja.lower() , obja.lower() , __lowerCamelCase ) __UpperCAmelCase : int = re.sub(obja.upper() , obja.upper() , __lowerCamelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __UpperCAmelCase : Union[str, Any] = blackify(lines[start_index - 1] + theoretical_code ) __UpperCAmelCase : Optional[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __UpperCAmelCase : int = lines[:start_index] + [theoretical_code] + lines[line_index:] __UpperCAmelCase : Union[str, Any] = start_index + 1 if overwrite and len(__lowerCamelCase ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(__lowerCamelCase ) return diffs def lowerCamelCase__ ( __lowerCamelCase : bool = False ): __UpperCAmelCase : Tuple = glob.glob(os.path.join(__lowerCamelCase , """**/*.py""" ) , recursive=__lowerCamelCase ) __UpperCAmelCase : Optional[int] = [] for filename in all_files: __UpperCAmelCase : str = is_copy_consistent(__lowerCamelCase , __lowerCamelCase ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(__lowerCamelCase ) > 0: __UpperCAmelCase : Union[str, Any] = """\n""".join(__lowerCamelCase ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": a : Dict = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") a : Optional[int] = parser.parse_args() check_copies(args.fix_and_overwrite)
114
1
"""simple docstring""" import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency SCREAMING_SNAKE_CASE_ : Any = { 'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' SCREAMING_SNAKE_CASE_ : str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def _snake_case ( UpperCAmelCase_ : str ): A__ = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _snake_case ( UpperCAmelCase_ : tuple ): return x[0] def _snake_case ( UpperCAmelCase_ : str ): A__ = get_letter_count(UpperCAmelCase_ ) A__ = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(UpperCAmelCase_ ) A__ = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=UpperCAmelCase_ ) A__ = """""".join(freq_to_letter[freq] ) A__ = list(freq_to_letter_str.items() ) freq_pairs.sort(key=UpperCAmelCase_ , reverse=UpperCAmelCase_ ) A__ = [freq_pair[1] for freq_pair in freq_pairs] return "".join(UpperCAmelCase_ ) def _snake_case ( UpperCAmelCase_ : str ): A__ = get_frequency_order(UpperCAmelCase_ ) A__ = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
69
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE_ : List[str] = '\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John",\n booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n month = aug # " 8-12",\n year = "2006",\n address = "Cambridge, Massachusetts, USA",\n publisher = "Association for Machine Translation in the Americas",\n url = "https://aclanthology.org/2006.amta-papers.25",\n pages = "223--231",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' SCREAMING_SNAKE_CASE_ : List[str] = '\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' SCREAMING_SNAKE_CASE_ : List[Any] = '\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self: Tuple ): """simple docstring""" if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[ """https://github.com/jhclark/tercom""", ] , ) def UpperCamelCase ( self: int , UpperCamelCase: Optional[int] , UpperCamelCase: Union[str, Any] , UpperCamelCase: bool = False , UpperCamelCase: bool = False , UpperCamelCase: bool = False , UpperCamelCase: bool = False , ): """simple docstring""" A__ = len(references[0] ) if any(len(UpperCamelCase ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) A__ = [[refs[i] for refs in references] for i in range(UpperCamelCase )] A__ = TER( normalized=UpperCamelCase , no_punct=UpperCamelCase , asian_support=UpperCamelCase , case_sensitive=UpperCamelCase , ) A__ = sb_ter.corpus_score(UpperCamelCase , UpperCamelCase ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
69
1
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowercase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: _snake_case : Any = TapasConfig.from_json_file(UpperCAmelCase_ ) # set absolute/relative position embeddings parameter _snake_case : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _snake_case : List[Any] = TapasForQuestionAnswering(config=UpperCAmelCase_ ) elif task == "WTQ": # run_task_main.py hparams _snake_case : str = 4 _snake_case : Tuple = True # hparam_utils.py hparams _snake_case : Optional[Any] = 0.6_6_4_6_9_4 _snake_case : Optional[Any] = 0.2_0_7_9_5_1 _snake_case : Any = 0.1_2_1_1_9_4 _snake_case : Optional[int] = True _snake_case : Dict = True _snake_case : Union[str, Any] = False _snake_case : List[Any] = 0.0_3_5_2_5_1_3 _snake_case : List[Any] = TapasForQuestionAnswering(config=UpperCAmelCase_ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _snake_case : List[Any] = 4 _snake_case : List[str] = False # hparam_utils.py hparams _snake_case : str = 3_6.4_5_1_9 _snake_case : Tuple = 0.9_0_3_4_2_1 _snake_case : Any = 2_2_2.0_8_8 _snake_case : Dict = True _snake_case : int = True _snake_case : Any = True _snake_case : str = 0.7_6_3_1_4_1 _snake_case : Any = TapasForQuestionAnswering(config=UpperCAmelCase_ ) elif task == "TABFACT": _snake_case : List[str] = TapasForSequenceClassification(config=UpperCAmelCase_ ) elif task == "MLM": _snake_case : List[str] = TapasForMaskedLM(config=UpperCAmelCase_ ) elif task == "INTERMEDIATE_PRETRAINING": _snake_case : Dict = TapasModel(config=UpperCAmelCase_ ) else: raise ValueError(F'''Task {task} not supported.''' ) print(F'''Building PyTorch model from configuration: {config}''' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Save pytorch-model (weights and configuration) print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(UpperCAmelCase_ ) # Save tokenizer files print(F'''Save tokenizer files to {pytorch_dump_path}''' ) _snake_case : List[str] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(UpperCAmelCase_ ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--task""", default="""SQA""", type=str, help="""Model task for which to convert a checkpoint. Defaults to SQA.""" ) parser.add_argument( """--reset_position_index_per_cell""", default=False, action="""store_true""", help="""Whether to use relative position embeddings or not. Defaults to True.""", ) parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--tapas_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained TAPAS model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
317
"""simple docstring""" _a : Tuple= 8.3_1_4_4_5_9_8 def __UpperCAmelCase ( UpperCAmelCase_ : float , UpperCAmelCase_ : float ) -> float: '''simple docstring''' if temperature < 0: raise Exception('Temperature cannot be less than 0 K' ) if molar_mass <= 0: raise Exception('Molar mass cannot be less than or equal to 0 kg/mol' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example _a : Any= 300 _a : Optional[Any]= 28 _a : Optional[int]= rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
172
0
"""simple docstring""" import re def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = re.compile( R"""^(?:0|94|\+94|0{2}94)""" R"""7(0|1|2|4|5|6|7|8)""" R"""(-| |)""" R"""\d{7}$""" ) return bool(re.search(UpperCamelCase__ , UpperCamelCase__ ) ) if __name__ == "__main__": _snake_case = '0094702343221' print(is_sri_lankan_phone_number(phone))
324
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _snake_case = logging.getLogger(__name__) _snake_case = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The input training data files (multiple files in glob format). ''' '''Very often splitting large files to smaller files can prevent tokenizer going out of memory''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) UpperCamelCase : bool = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) UpperCamelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase : float = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) UpperCamelCase : int = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) UpperCamelCase : int = field( default=-1 , metadata={ '''help''': ( '''Optional input sequence length after tokenization.''' '''The training dataset will be truncated in block of this size for training.''' '''Default to the model max input length for single sentence inputs (take into account special tokens).''' ) } , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , ): '''simple docstring''' def _dataset(UpperCamelCase__ , UpperCamelCase__=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , ref_path=UpperCamelCase__ , ) return LineByLineTextDataset(tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: _a : str = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _a : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: _a : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: _a : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) _a : List[Any] = AutoModelWithLMHead.from_config(UpperCamelCase__ ) model.resize_token_embeddings(len(UpperCamelCase__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: _a : int = tokenizer.max_len # Our input block size will be the max possible for the model else: _a : Optional[Any] = min(data_args.block_size , tokenizer.max_len ) # Get datasets _a : Optional[Any] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _a : Optional[int] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , evaluate=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _a : Any = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: _a : Union[str, Any] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase__ , mlm_probability=data_args.mlm_probability ) else: _a : str = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , data_collator=UpperCamelCase__ , train_dataset=UpperCamelCase__ , eval_dataset=UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _a : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : int = trainer.evaluate() _a : Dict = math.exp(eval_output["""eval_loss"""] ) _a : Union[str, Any] = {"""perplexity""": perplexity} _a : Optional[Any] = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase__ ) return results def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
1
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _lowerCAmelCase : Tuple = { "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 : Union[str, Any] = F"{src_lang}-{tgt_lang}" _lowerCAmelCase : Optional[int] = F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) _lowerCAmelCase : Any = os.path.join(_lowerCamelCase , "README.md" ) print(F"Generating {path}" ) with open(_lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(_lowerCamelCase ) # make sure we are under the root of the project _snake_case = Path(__file__).resolve().parent.parent.parent _snake_case = repo_dir / "model_cards" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: _snake_case, _snake_case, _snake_case = model_name.split("-") _snake_case = model_cards_dir / "facebook" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
36
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES A__: List[Any] = logging.get_logger(__name__) A__: Any = OrderedDict( [ # Base model mapping ('''albert''', '''FlaxAlbertModel'''), ('''bart''', '''FlaxBartModel'''), ('''beit''', '''FlaxBeitModel'''), ('''bert''', '''FlaxBertModel'''), ('''big_bird''', '''FlaxBigBirdModel'''), ('''blenderbot''', '''FlaxBlenderbotModel'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallModel'''), ('''clip''', '''FlaxCLIPModel'''), ('''distilbert''', '''FlaxDistilBertModel'''), ('''electra''', '''FlaxElectraModel'''), ('''gpt-sw3''', '''FlaxGPT2Model'''), ('''gpt2''', '''FlaxGPT2Model'''), ('''gpt_neo''', '''FlaxGPTNeoModel'''), ('''gptj''', '''FlaxGPTJModel'''), ('''longt5''', '''FlaxLongT5Model'''), ('''marian''', '''FlaxMarianModel'''), ('''mbart''', '''FlaxMBartModel'''), ('''mt5''', '''FlaxMT5Model'''), ('''opt''', '''FlaxOPTModel'''), ('''pegasus''', '''FlaxPegasusModel'''), ('''regnet''', '''FlaxRegNetModel'''), ('''resnet''', '''FlaxResNetModel'''), ('''roberta''', '''FlaxRobertaModel'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormModel'''), ('''roformer''', '''FlaxRoFormerModel'''), ('''t5''', '''FlaxT5Model'''), ('''vision-text-dual-encoder''', '''FlaxVisionTextDualEncoderModel'''), ('''vit''', '''FlaxViTModel'''), ('''wav2vec2''', '''FlaxWav2Vec2Model'''), ('''whisper''', '''FlaxWhisperModel'''), ('''xglm''', '''FlaxXGLMModel'''), ('''xlm-roberta''', '''FlaxXLMRobertaModel'''), ] ) A__: Dict = OrderedDict( [ # Model for pre-training mapping ('''albert''', '''FlaxAlbertForPreTraining'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForPreTraining'''), ('''big_bird''', '''FlaxBigBirdForPreTraining'''), ('''electra''', '''FlaxElectraForPreTraining'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ('''wav2vec2''', '''FlaxWav2Vec2ForPreTraining'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) A__: Optional[int] = OrderedDict( [ # Model for Masked LM mapping ('''albert''', '''FlaxAlbertForMaskedLM'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForMaskedLM'''), ('''big_bird''', '''FlaxBigBirdForMaskedLM'''), ('''distilbert''', '''FlaxDistilBertForMaskedLM'''), ('''electra''', '''FlaxElectraForMaskedLM'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) A__: Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''blenderbot''', '''FlaxBlenderbotForConditionalGeneration'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallForConditionalGeneration'''), ('''encoder-decoder''', '''FlaxEncoderDecoderModel'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''marian''', '''FlaxMarianMTModel'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''pegasus''', '''FlaxPegasusForConditionalGeneration'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ] ) A__: Optional[Any] = OrderedDict( [ # Model for Image-classsification ('''beit''', '''FlaxBeitForImageClassification'''), ('''regnet''', '''FlaxRegNetForImageClassification'''), ('''resnet''', '''FlaxResNetForImageClassification'''), ('''vit''', '''FlaxViTForImageClassification'''), ] ) A__: List[Any] = OrderedDict( [ ('''vision-encoder-decoder''', '''FlaxVisionEncoderDecoderModel'''), ] ) A__: int = OrderedDict( [ # Model for Causal LM mapping ('''bart''', '''FlaxBartForCausalLM'''), ('''bert''', '''FlaxBertForCausalLM'''), ('''big_bird''', '''FlaxBigBirdForCausalLM'''), ('''electra''', '''FlaxElectraForCausalLM'''), ('''gpt-sw3''', '''FlaxGPT2LMHeadModel'''), ('''gpt2''', '''FlaxGPT2LMHeadModel'''), ('''gpt_neo''', '''FlaxGPTNeoForCausalLM'''), ('''gptj''', '''FlaxGPTJForCausalLM'''), ('''opt''', '''FlaxOPTForCausalLM'''), ('''roberta''', '''FlaxRobertaForCausalLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForCausalLM'''), ('''xglm''', '''FlaxXGLMForCausalLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForCausalLM'''), ] ) A__: Optional[Any] = OrderedDict( [ # Model for Sequence Classification mapping ('''albert''', '''FlaxAlbertForSequenceClassification'''), ('''bart''', '''FlaxBartForSequenceClassification'''), ('''bert''', '''FlaxBertForSequenceClassification'''), ('''big_bird''', '''FlaxBigBirdForSequenceClassification'''), ('''distilbert''', '''FlaxDistilBertForSequenceClassification'''), ('''electra''', '''FlaxElectraForSequenceClassification'''), ('''mbart''', '''FlaxMBartForSequenceClassification'''), ('''roberta''', '''FlaxRobertaForSequenceClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForSequenceClassification'''), ('''roformer''', '''FlaxRoFormerForSequenceClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForSequenceClassification'''), ] ) A__: Optional[Any] = OrderedDict( [ # Model for Question Answering mapping ('''albert''', '''FlaxAlbertForQuestionAnswering'''), ('''bart''', '''FlaxBartForQuestionAnswering'''), ('''bert''', '''FlaxBertForQuestionAnswering'''), ('''big_bird''', '''FlaxBigBirdForQuestionAnswering'''), ('''distilbert''', '''FlaxDistilBertForQuestionAnswering'''), ('''electra''', '''FlaxElectraForQuestionAnswering'''), ('''mbart''', '''FlaxMBartForQuestionAnswering'''), ('''roberta''', '''FlaxRobertaForQuestionAnswering'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForQuestionAnswering'''), ('''roformer''', '''FlaxRoFormerForQuestionAnswering'''), ('''xlm-roberta''', '''FlaxXLMRobertaForQuestionAnswering'''), ] ) A__: List[Any] = OrderedDict( [ # Model for Token Classification mapping ('''albert''', '''FlaxAlbertForTokenClassification'''), ('''bert''', '''FlaxBertForTokenClassification'''), ('''big_bird''', '''FlaxBigBirdForTokenClassification'''), ('''distilbert''', '''FlaxDistilBertForTokenClassification'''), ('''electra''', '''FlaxElectraForTokenClassification'''), ('''roberta''', '''FlaxRobertaForTokenClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForTokenClassification'''), ('''roformer''', '''FlaxRoFormerForTokenClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForTokenClassification'''), ] ) A__: Optional[int] = OrderedDict( [ # Model for Multiple Choice mapping ('''albert''', '''FlaxAlbertForMultipleChoice'''), ('''bert''', '''FlaxBertForMultipleChoice'''), ('''big_bird''', '''FlaxBigBirdForMultipleChoice'''), ('''distilbert''', '''FlaxDistilBertForMultipleChoice'''), ('''electra''', '''FlaxElectraForMultipleChoice'''), ('''roberta''', '''FlaxRobertaForMultipleChoice'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMultipleChoice'''), ('''roformer''', '''FlaxRoFormerForMultipleChoice'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMultipleChoice'''), ] ) A__: Optional[Any] = OrderedDict( [ ('''bert''', '''FlaxBertForNextSentencePrediction'''), ] ) A__: Dict = OrderedDict( [ ('''speech-encoder-decoder''', '''FlaxSpeechEncoderDecoderModel'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ] ) A__: Dict = OrderedDict( [ ('''whisper''', '''FlaxWhisperForAudioClassification'''), ] ) A__: Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) A__: List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) A__: str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) A__: int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) A__: str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) A__: List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) A__: List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) A__: int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) A__: str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) A__: Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) A__: Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) A__: Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) A__: str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) A__: Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_MAPPING A__: int = auto_class_update(FlaxAutoModel) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_PRETRAINING_MAPPING A__: Dict = auto_class_update(FlaxAutoModelForPreTraining, head_doc='''pretraining''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING A__: Any = auto_class_update(FlaxAutoModelForCausalLM, head_doc='''causal language modeling''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_MASKED_LM_MAPPING A__: List[Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='''masked language modeling''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING A__: int = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='''sequence-to-sequence language modeling''', checkpoint_for_example='''t5-base''' ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A__: Tuple = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='''sequence classification''' ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING A__: Optional[Any] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='''question answering''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A__: str = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='''token classification''' ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING A__: List[Any] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='''multiple choice''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING A__: Any = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='''next sentence prediction''' ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING A__: Dict = auto_class_update( FlaxAutoModelForImageClassification, head_doc='''image classification''' ) class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING A__: Dict = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='''vision-to-text modeling''') class _a ( _BaseAutoModelClass): """simple docstring""" UpperCamelCase__ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING A__: List[Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='''sequence-to-sequence speech-to-text modeling''' )
149
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowerCAmelCase__ : List[str] =logging.get_logger(__name__) def __lowercase ( a__ ) -> List[int]: if isinstance(a__ , np.ndarray ): return list(tensor.shape ) __SCREAMING_SNAKE_CASE = tf.shape(a__ ) if tensor.shape == tf.TensorShape(a__ ): return dynamic __SCREAMING_SNAKE_CASE = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(a__ )] def __lowercase ( a__ , a__ = None , a__ = None ) -> tf.Tensor: return tf.nn.softmax(logits=logits + 1E-9 , axis=a__ , name=a__ ) def __lowercase ( a__ , a__ , a__ , a__=1E-5 , a__=-1 ) -> List[str]: # This is a very simplified functional layernorm, designed to duplicate # the functionality of PyTorch nn.functional.layer_norm when this is needed to port # models in Transformers. if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(a__ , a__ ): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' ) # Get mean and variance on the axis to be normalized __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.nn.moments(a__ , axes=[axis] , keepdims=a__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis __SCREAMING_SNAKE_CASE = [1] * inputs.shape.rank __SCREAMING_SNAKE_CASE = shape_list(a__ )[axis] __SCREAMING_SNAKE_CASE = tf.reshape(a__ , a__ ) __SCREAMING_SNAKE_CASE = tf.reshape(a__ , a__ ) # Compute layer normalization using the batch_normalization # function. __SCREAMING_SNAKE_CASE = tf.nn.batch_normalization( a__ , a__ , a__ , offset=a__ , scale=a__ , variance_epsilon=a__ , ) return outputs def __lowercase ( a__ , a__=0 , a__=-1 ) -> Tuple: # Replicates the behavior of torch.flatten in TF # If end_dim or start_dim is negative, count them from the end if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input __SCREAMING_SNAKE_CASE = tf.shape(a__ ) __SCREAMING_SNAKE_CASE = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) __SCREAMING_SNAKE_CASE = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(a__ , a__ ) def __lowercase ( a__ ) -> tf.Tensor: if not isinstance(a__ , tf.Tensor ): __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: __SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: __SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) __SCREAMING_SNAKE_CASE = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def __lowercase ( a__ , a__ , a__ = "input_ids" ) -> None: tf.debugging.assert_less( a__ , tf.cast(a__ , dtype=tensor.dtype ) , message=( f"""The maximum value of {tensor_name} ({tf.math.reduce_max(a__ )}) must be smaller than the embedding """ f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time.""" ) , ) def __lowercase ( a__ , a__ , a__ ) -> str: __SCREAMING_SNAKE_CASE = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. __SCREAMING_SNAKE_CASE = [x for x in data if len(a__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """ f"""bytes: {bad_attributes}""" ) __SCREAMING_SNAKE_CASE = np.asarray(a__ ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = np.array_split(a__ , a__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 __SCREAMING_SNAKE_CASE = np.array_split(a__ , a__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(a__ ): __SCREAMING_SNAKE_CASE = chunk_data else: __SCREAMING_SNAKE_CASE = data def __lowercase ( a__ , a__ ) -> int: if name in group.attrs: __SCREAMING_SNAKE_CASE = [n.decode('utf8' ) if hasattr(a__ , 'decode' ) else n for n in group.attrs[name]] else: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8' ) if hasattr(a__ , 'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] ) chunk_id += 1 return data def __lowercase ( a__ ) -> Any: def _expand_single_ad_tensor(a__ ): if isinstance(a__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(a__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , a__ )
118
from __future__ import annotations from collections.abc import Generator def __lowercase ( ) -> Generator[int, None, None]: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 2 while True: __SCREAMING_SNAKE_CASE = factor_map.pop(a__ , a__ ) if factor: __SCREAMING_SNAKE_CASE = factor + prime while x in factor_map: x += factor __SCREAMING_SNAKE_CASE = factor else: __SCREAMING_SNAKE_CASE = prime yield prime prime += 1 def __lowercase ( a__ = 1E10 ) -> int: __SCREAMING_SNAKE_CASE = sieve() __SCREAMING_SNAKE_CASE = 1 while True: __SCREAMING_SNAKE_CASE = next(a__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(a__ ) n += 2 if __name__ == "__main__": print(solution())
118
1
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : List[str] = { """huggingface/time-series-transformer-tourism-monthly""": ( """https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json""" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class _UpperCAmelCase ( __snake_case ): '''simple docstring''' lowerCamelCase__ ='time_series_transformer' lowerCamelCase__ ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__(self , a_ = None , a_ = None , a_ = "student_t" , a_ = "nll" , a_ = 1 , a_ = [1, 2, 3, 4, 5, 6, 7] , a_ = "mean" , a_ = 0 , a_ = 0 , a_ = 0 , a_ = 0 , a_ = None , a_ = None , a_ = 32 , a_ = 32 , a_ = 2 , a_ = 2 , a_ = 2 , a_ = 2 , a_ = True , a_ = "gelu" , a_ = 64 , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1_00 , a_ = 0.02 , a_=True , **a_ , ): '''simple docstring''' __snake_case : Union[str, Any] = prediction_length __snake_case : List[str] = context_length or prediction_length __snake_case : Tuple = distribution_output __snake_case : Union[str, Any] = loss __snake_case : Tuple = input_size __snake_case : Optional[Any] = num_time_features __snake_case : Tuple = lags_sequence __snake_case : Optional[int] = scaling __snake_case : Optional[Any] = num_dynamic_real_features __snake_case : Optional[Any] = num_static_real_features __snake_case : List[str] = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(a_ ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) __snake_case : Dict = cardinality else: __snake_case : Optional[int] = [0] if embedding_dimension and num_static_categorical_features > 0: if len(a_ ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) __snake_case : Dict = embedding_dimension else: __snake_case : int = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __snake_case : int = num_parallel_samples # Transformer architecture configuration __snake_case : Union[str, Any] = input_size * len(a_ ) + self._number_of_features __snake_case : Any = d_model __snake_case : Union[str, Any] = encoder_attention_heads __snake_case : Any = decoder_attention_heads __snake_case : Any = encoder_ffn_dim __snake_case : List[Any] = decoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Union[str, Any] = decoder_layers __snake_case : int = dropout __snake_case : List[str] = attention_dropout __snake_case : Optional[int] = activation_dropout __snake_case : Dict = encoder_layerdrop __snake_case : Optional[Any] = decoder_layerdrop __snake_case : int = activation_function __snake_case : Union[str, Any] = init_std __snake_case : int = use_cache super().__init__(is_encoder_decoder=a_ , **a_ ) @property def SCREAMING_SNAKE_CASE (self ): '''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 )
102
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowerCAmelCase ( __a , unittest.TestCase ): _lowercase =None _lowercase =BloomTokenizerFast _lowercase =BloomTokenizerFast _lowercase =True _lowercase =False _lowercase ='''tokenizer_file''' _lowercase ={'''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''unk_token''': '''<unk>''', '''pad_token''': '''<pad>'''} def __a ( self ) -> Dict: super().setUp() lowerCAmelCase_ = BloomTokenizerFast.from_pretrained("bigscience/tokenizer" ) tokenizer.save_pretrained(self.tmpdirname ) def __a ( self , **_UpperCamelCase ) -> Tuple: kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCamelCase ) def __a ( self ) -> List[str]: lowerCAmelCase_ = self.get_rust_tokenizer() lowerCAmelCase_ = ["The quick brown fox</s>", "jumps over the lazy dog</s>"] lowerCAmelCase_ = [[2_175, 23_714, 73_173, 144_252, 2], [77, 132_619, 3_478, 368, 109_586, 35_433, 2]] lowerCAmelCase_ = tokenizer.batch_encode_plus(_UpperCamelCase )["input_ids"] self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = tokenizer.batch_decode(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) def __a ( self , _UpperCamelCase=6 ) -> Tuple: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCAmelCase_ = self.rust_tokenizer_class.from_pretrained(_UpperCamelCase , **_UpperCamelCase ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input lowerCAmelCase_ = "This is a simple input" lowerCAmelCase_ = ["This is a simple input 1", "This is a simple input 2"] lowerCAmelCase_ = ("This is a simple input", "This is a pair") lowerCAmelCase_ = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests try: tokenizer_r.encode(_UpperCamelCase , max_length=_UpperCamelCase ) tokenizer_r.encode_plus(_UpperCamelCase , max_length=_UpperCamelCase ) tokenizer_r.batch_encode_plus(_UpperCamelCase , max_length=_UpperCamelCase ) tokenizer_r.encode(_UpperCamelCase , max_length=_UpperCamelCase ) tokenizer_r.batch_encode_plus(_UpperCamelCase , max_length=_UpperCamelCase ) except ValueError: self.fail("Bloom Tokenizer should be able to deal with padding" ) lowerCAmelCase_ = None # Hotfixing padding = None self.assertRaises(_UpperCamelCase , tokenizer_r.encode , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" ) # Simple input self.assertRaises(_UpperCamelCase , tokenizer_r.encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" ) # Simple input self.assertRaises( _UpperCamelCase , tokenizer_r.batch_encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" , ) # Pair input self.assertRaises(_UpperCamelCase , tokenizer_r.encode , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" ) # Pair input self.assertRaises(_UpperCamelCase , tokenizer_r.encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" ) # Pair input self.assertRaises( _UpperCamelCase , tokenizer_r.batch_encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding="max_length" , ) def __a ( self ) -> Any: lowerCAmelCase_ = self.get_rust_tokenizer() lowerCAmelCase_ = load_dataset("xnli" , "all_languages" , split="test" , streaming=_UpperCamelCase ) lowerCAmelCase_ = next(iter(_UpperCamelCase ) )["premise"] # pick up one data lowerCAmelCase_ = list(sample_data.values() ) lowerCAmelCase_ = list(map(tokenizer.encode , _UpperCamelCase ) ) lowerCAmelCase_ = [tokenizer.decode(_UpperCamelCase , clean_up_tokenization_spaces=_UpperCamelCase ) for x in output_tokens] self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) def __a ( self ) -> List[Any]: # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
231
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class snake_case__ : """simple docstring""" lowerCamelCase = XGLMConfig lowerCamelCase = {} lowerCamelCase = """gelu""" def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any]=14 , UpperCamelCase__ : Optional[int]=7 , UpperCamelCase__ : str=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=99 , UpperCamelCase__ : Optional[Any]=32 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : str="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : int=0.02 , ) -> List[str]: """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Dict = batch_size snake_case : int = seq_length snake_case : str = is_training snake_case : List[str] = use_input_mask snake_case : Dict = use_labels snake_case : str = vocab_size snake_case : Tuple = d_model snake_case : Union[str, Any] = num_hidden_layers snake_case : str = num_attention_heads snake_case : int = ffn_dim snake_case : Optional[int] = activation_function snake_case : Optional[Any] = activation_dropout snake_case : Dict = attention_dropout snake_case : str = max_position_embeddings snake_case : Tuple = initializer_range snake_case : int = None snake_case : List[Any] = 0 snake_case : int = 2 snake_case : Dict = 1 def lowerCAmelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return XGLMConfig.from_pretrained('''facebook/xglm-564M''' ) def lowerCAmelCase ( self : Any ) -> str: """simple docstring""" snake_case : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) snake_case : List[Any] = None if self.use_input_mask: snake_case : str = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : Dict = self.get_config() snake_case : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[str] ) -> Dict: """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=UpperCamelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=UpperCamelCase__ , ) def lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" snake_case : Any = self.prepare_config_and_inputs() ( ( snake_case ) ,( snake_case ) ,( snake_case ) ,( snake_case ) , ) : Union[str, Any] = config_and_inputs snake_case : List[Any] = { '''input_ids''': input_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_tf class snake_case__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" lowerCamelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () lowerCamelCase = (TFXGLMForCausalLM,) if is_tf_available() else () lowerCamelCase = ( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" snake_case : List[Any] = TFXGLMModelTester(self ) snake_case : List[Any] = ConfigTester(self , config_class=UpperCamelCase__ , n_embd=37 ) def lowerCAmelCase ( self : str ) -> int: """simple docstring""" self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Union[str, Any] = TFXGLMModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.''' ) def lowerCAmelCase ( self : int ) -> Tuple: """simple docstring""" super().test_resize_token_embeddings() @require_tf class snake_case__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCAmelCase ( self : str , UpperCamelCase__ : Any=True ) -> Optional[int]: """simple docstring""" snake_case : Dict = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) snake_case : List[Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off snake_case : List[Any] = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on snake_case : int = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase__ ) @slow def lowerCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" snake_case : str = XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) snake_case : Dict = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) tf.random.set_seed(0 ) snake_case : List[Any] = tokenizer('''Today is a nice day and''' , return_tensors='''tf''' ) snake_case : Union[str, Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(''':/CPU:0''' ): snake_case : Optional[int] = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ , seed=[7, 0] ) snake_case : Any = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCamelCase__ ) snake_case : Tuple = ( '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due''' ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) @slow def lowerCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" snake_case : List[Any] = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) snake_case : List[Any] = XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) snake_case : List[Any] = '''left''' # use different length sentences to test batching snake_case : int = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When''', '''Hello, my dog is a little''', ] snake_case : Dict = tokenizer(UpperCamelCase__ , return_tensors='''tf''' , padding=UpperCamelCase__ ) snake_case : str = inputs['''input_ids'''] snake_case : Union[str, Any] = model.generate(input_ids=UpperCamelCase__ , attention_mask=inputs['''attention_mask'''] , max_new_tokens=12 ) snake_case : Tuple = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids snake_case : List[Any] = model.generate(input_ids=UpperCamelCase__ , max_new_tokens=12 ) snake_case : Union[str, Any] = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids snake_case : Dict = model.generate(input_ids=UpperCamelCase__ , max_new_tokens=12 ) snake_case : Optional[int] = tokenizer.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) snake_case : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCamelCase__ ) snake_case : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCamelCase__ ) snake_case : Union[str, Any] = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ''' '''a single''', '''Hello, my dog is a little bit of a shy one, but he is very friendly''', ] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , [non_padded_sentence, padded_sentence] )
83
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class snake_case__ ( unittest.TestCase ): """simple docstring""" lowerCamelCase = StableDiffusionLDMaDPipeline lowerCamelCase = TEXT_TO_IMAGE_PARAMS lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) snake_case : str = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) snake_case : Dict = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=UpperCamelCase__ , set_alpha_to_one=UpperCamelCase__ , ) torch.manual_seed(0 ) snake_case : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) snake_case : int = CLIPTextModel(UpperCamelCase__ ) snake_case : Tuple = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case : str = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowerCAmelCase ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str=0 ) -> Optional[int]: """simple docstring""" if str(UpperCamelCase__ ).startswith('''mps''' ): snake_case : Optional[int] = torch.manual_seed(UpperCamelCase__ ) else: snake_case : Optional[int] = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Tuple = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Any ) -> str: """simple docstring""" snake_case : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case : List[Any] = self.get_dummy_components() snake_case : str = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Union[str, Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : List[str] = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : Tuple = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : int = output.rgb, output.depth snake_case : str = rgb[0, -3:, -3:, -1] snake_case : Union[str, Any] = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case : int = np.array( [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] ) snake_case : str = np.array([103.46_727, 85.812_004, 87.849_236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2 def lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" snake_case : int = self.get_dummy_components() snake_case : Any = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Optional[Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : int = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : str = 3 * [inputs['''prompt''']] # forward snake_case : Union[str, Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Tuple = rgb_slice_a[0, -3:, -3:, -1] snake_case : List[str] = depth_slice_a[0, -3:, -1] snake_case : int = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : Optional[int] = 3 * [inputs.pop('''prompt''' )] snake_case : Dict = ldmad_pipe.tokenizer( UpperCamelCase__ , padding='''max_length''' , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=UpperCamelCase__ , return_tensors='''pt''' , ) snake_case : Optional[Any] = text_inputs['''input_ids'''].to(UpperCamelCase__ ) snake_case : Any = ldmad_pipe.text_encoder(UpperCamelCase__ )[0] snake_case : Tuple = prompt_embeds # forward snake_case : List[Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Dict = output.rgb, output.depth snake_case : Any = rgb_slice_a[0, -3:, -3:, -1] snake_case : Dict = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4 def lowerCAmelCase ( self : str ) -> List[Any]: """simple docstring""" snake_case : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case : Dict = self.get_dummy_components() snake_case : List[str] = PNDMScheduler(skip_prk_steps=UpperCamelCase__ ) snake_case : Optional[Any] = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Dict = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Dict = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : str = '''french fries''' snake_case : List[str] = ldmad_pipe(**UpperCamelCase__ , negative_prompt=UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Union[str, Any] = rgb[0, -3:, -3:, -1] snake_case : int = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case : Dict = np.array( [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] ) snake_case : Any = np.array([107.84_738, 84.62_802, 89.962_135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2 @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any]="cpu" , UpperCamelCase__ : Optional[int]=torch.floataa , UpperCamelCase__ : Union[str, Any]=0 ) -> Any: """simple docstring""" snake_case : Any = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Optional[Any] = np.random.RandomState(UpperCamelCase__ ).standard_normal((1, 4, 64, 64) ) snake_case : Any = torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ , dtype=UpperCamelCase__ ) snake_case : List[Any] = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" snake_case : Dict = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d''' ) snake_case : Optional[Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Any = self.get_inputs(UpperCamelCase__ ) snake_case : str = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : List[Any] = output.rgb, output.depth snake_case : Optional[Any] = rgb[0, -3:, -3:, -1].flatten() snake_case : Tuple = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) snake_case : Optional[Any] = np.array( [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] ) snake_case : str = np.array( [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3 @nightly @require_torch_gpu class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Any="cpu" , UpperCamelCase__ : Optional[int]=torch.floataa , UpperCamelCase__ : Optional[int]=0 ) -> str: """simple docstring""" snake_case : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Optional[Any] = np.random.RandomState(UpperCamelCase__ ).standard_normal((1, 4, 64, 64) ) snake_case : int = torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ , dtype=UpperCamelCase__ ) snake_case : List[str] = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 50, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" snake_case : Optional[Any] = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d''' ).to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Dict = self.get_inputs(UpperCamelCase__ ) snake_case : str = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Union[str, Any] = 0.495_586 snake_case : Tuple = 0.33_795_515 snake_case : Dict = 112.48_518 snake_case : Optional[int] = 98.489_746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3 def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" snake_case : Optional[int] = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d-4c''' ).to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : int = self.get_inputs(UpperCamelCase__ ) snake_case : List[Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Tuple = 0.4_194_127 snake_case : Optional[Any] = 0.35_375_586 snake_case : Any = 0.5_638_502 snake_case : int = 0.34_686_103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3
83
1
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> List[str]: _enforce_args(lowerCamelCase_ , lowerCamelCase_ ) if n == 0: return 0 _lowercase : Union[str, Any] = float('-inf' ) for i in range(1 , n + 1 ): _lowercase : int = max( lowerCamelCase_ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCamelCase_ ) ) return max_revue def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Any: _enforce_args(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : Optional[Any] = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _lowercase : Any = float('-inf' ) for i in range(1 , n + 1 ): _lowercase : List[Any] = max( lowerCamelCase_ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCamelCase_ , lowerCamelCase_ ) , ) _lowercase : Dict = max_revenue return max_rev[n] def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]: _enforce_args(lowerCamelCase_ , lowerCamelCase_ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _lowercase : int = [float('-inf' ) for _ in range(n + 1 )] _lowercase : str = 0 for i in range(1 , n + 1 ): _lowercase : Tuple = max_rev[i] for j in range(1 , i + 1 ): _lowercase : Any = max(lowerCamelCase_ , prices[j - 1] + max_rev[i - j] ) _lowercase : Optional[Any] = max_revenue_i return max_rev[n] def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> List[str]: if n < 0: _lowercase : Optional[int] = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCamelCase_ ) if n > len(lowerCamelCase_ ): _lowercase : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' F'''Got n = {n} but length of prices = {len(lowerCamelCase_ )}''' ) raise ValueError(lowerCamelCase_ ) def UpperCamelCase_( ) -> Optional[int]: _lowercase : List[str] = [6, 10, 12, 15, 20, 23] _lowercase : Any = len(lowerCamelCase_ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _lowercase : Tuple = 36 _lowercase : int = top_down_cut_rod(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : Tuple = bottom_up_cut_rod(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : int = naive_cut_rod_recursive(lowerCamelCase_ , lowerCamelCase_ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
21
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'google/vivit-b-16x2-kinetics400': ( 'https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : Optional[int] = """vivit""" def __init__( self : List[str] , _UpperCAmelCase : List[Any]=2_24 , _UpperCAmelCase : List[str]=32 , _UpperCAmelCase : Any=[2, 16, 16] , _UpperCAmelCase : int=3 , _UpperCAmelCase : Optional[Any]=7_68 , _UpperCAmelCase : Union[str, Any]=12 , _UpperCAmelCase : Dict=12 , _UpperCAmelCase : Optional[Any]=30_72 , _UpperCAmelCase : Optional[int]="gelu_fast" , _UpperCAmelCase : Union[str, Any]=0.0 , _UpperCAmelCase : Tuple=0.0 , _UpperCAmelCase : Optional[int]=0.02 , _UpperCAmelCase : List[Any]=1E-06 , _UpperCAmelCase : List[str]=True , **_UpperCAmelCase : List[Any] , ): """simple docstring""" UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = initializer_range UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = image_size UpperCAmelCase__ = num_frames UpperCAmelCase__ = tubelet_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = qkv_bias super().__init__(**_UpperCAmelCase )
346
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def SCREAMING_SNAKE_CASE_ ( )-> Generator[int, None, None]: _lowerCamelCase = {} _lowerCamelCase = 2 while True: _lowerCamelCase = factor_map.pop(lowerCamelCase_ , lowerCamelCase_ ) if factor: _lowerCamelCase = factor + prime while x in factor_map: x += factor _lowerCamelCase = factor else: _lowerCamelCase = prime yield prime prime += 1 def SCREAMING_SNAKE_CASE_ ( snake_case : Dict = 1e10 )-> int: _lowerCamelCase = sieve() _lowerCamelCase = 1 while True: _lowerCamelCase = next(lowerCamelCase_ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(lowerCamelCase_ ) n += 2 if __name__ == "__main__": print(solution())
367
"""simple docstring""" def SCREAMING_SNAKE_CASE_ ( snake_case : list )-> list: def merge(snake_case : list , snake_case : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(snake_case ) <= 1: return collection _lowerCamelCase = len(snake_case ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() A_ : int =input("""Enter numbers separated by a comma:\n""").strip() A_ : Dict =[int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
80
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __UpperCAmelCase = logging.getLogger(__name__) def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" return (preds == labels).mean() @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) SCREAMING_SNAKE_CASE__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) SCREAMING_SNAKE_CASE__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) SCREAMING_SNAKE_CASE__ = field( default=lowercase_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , lowerCamelCase_ ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE : Dict = processors[data_args.task_name]() SCREAMING_SNAKE_CASE : Optional[int] = processor.get_labels() SCREAMING_SNAKE_CASE : List[str] = len(lowerCamelCase_ ) except KeyError: raise ValueError("""Task not found: %s""" % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCamelCase_ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=lowerCamelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets SCREAMING_SNAKE_CASE : Optional[Any] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowerCamelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE : Dict = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowerCamelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(lowerCamelCase_ ) -> Dict: SCREAMING_SNAKE_CASE : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(lowerCamelCase_ , p.label_ids )} # Data collator SCREAMING_SNAKE_CASE : List[Any] = DataCollatorWithPadding(lowerCamelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE : Any = Trainer( model=lowerCamelCase_ , args=lowerCamelCase_ , train_dataset=lowerCamelCase_ , eval_dataset=lowerCamelCase_ , compute_metrics=lowerCamelCase_ , data_collator=lowerCamelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE : Optional[Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE : Optional[Any] = trainer.evaluate() SCREAMING_SNAKE_CASE : str = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_master(): with open(lowerCamelCase_ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , lowerCamelCase_ , lowerCamelCase_ ) writer.write("""%s = %s\n""" % (key, value) ) results.update(lowerCamelCase_ ) return results def __A ( lowerCamelCase_ ): """simple docstring""" main() if __name__ == "__main__": main()
323
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : NestedDataStructureLike[PathLike] , lowerCamelCase_ : Optional[NamedSplit] = None , lowerCamelCase_ : Optional[Features] = None , lowerCamelCase_ : str = None , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[int] = None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' super().__init__( lowerCamelCase_ , split=lowerCamelCase_ , features=lowerCamelCase_ , cache_dir=lowerCamelCase_ , keep_in_memory=lowerCamelCase_ , streaming=lowerCamelCase_ , num_proc=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : int = path_or_paths if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE : Optional[int] = Text( cache_dir=lowerCamelCase_ , data_files=lowerCamelCase_ , features=lowerCamelCase_ , **lowerCamelCase_ , ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE : int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = None self.builder.download_and_prepare( download_config=lowerCamelCase_ , download_mode=lowerCamelCase_ , verification_mode=lowerCamelCase_ , base_path=lowerCamelCase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE : int = self.builder.as_dataset( split=self.split , verification_mode=lowerCamelCase_ , in_memory=self.keep_in_memory ) return dataset
323
1
import argparse import os import re a_ = "src/transformers/models/auto" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict a_ = re.compile(R"""[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict""") # re pattern that matches identifiers in mappings a_ = re.compile(R"""\s*\(\s*\"(\S[^\"]+)\"""") def __lowercase ( snake_case_ : Any ,snake_case_ : bool = False ) ->List[Any]: '''simple docstring''' with open(snake_case_ ,'''r''' ,encoding='''utf-8''' ) as f: __A : List[Any] = f.read() __A : Optional[Any] = content.split('''\n''' ) __A : Tuple = [] __A : Optional[Any] = 0 while line_idx < len(snake_case_ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: __A : int = len(re.search(r'''^(\s*)\S''' ,lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(''' ''' * indent + '''(''' ): new_lines.append(lines[line_idx] ) line_idx += 1 __A : int = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": __A : List[Any] = line_idx while not lines[line_idx].startswith(''' ''' * indent + ''')''' ): line_idx += 1 blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers __A : Tuple = sorted(snake_case_ ,key=lambda snake_case_ : _re_identifier.search(snake_case_ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(snake_case_ ,'''w''' ,encoding='''utf-8''' ) as f: f.write('''\n'''.join(snake_case_ ) ) elif "\n".join(snake_case_ ) != content: return True def __lowercase ( snake_case_ : bool = False ) ->List[Any]: '''simple docstring''' __A : int = [os.path.join(snake_case_ ,snake_case_ ) for f in os.listdir(snake_case_ ) if f.endswith('''.py''' )] __A : str = [sort_auto_mapping(snake_case_ ,overwrite=snake_case_ ) for fname in fnames] if not overwrite and any(snake_case_ ): __A : Tuple = [f for f, d in zip(snake_case_ ,snake_case_ ) if d] raise ValueError( F"""The following files have auto mappings that need sorting: {', '.join(snake_case_ )}. Run `make style` to fix""" ''' this.''' ) if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") a_ = parser.parse_args() sort_all_auto_mappings(not args.check_only)
357
"""simple docstring""" 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 __snake_case ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" _lowerCamelCase = XLMTokenizer _lowerCamelCase = False def UpperCamelCase__( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __A : Tuple = [ '''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>''', ] __A : Dict = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) __A : Union[str, Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__lowerCamelCase ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__lowerCamelCase ) ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : Optional[int] = '''lower newer''' __A : int = '''lower newer''' return input_text, output_text def UpperCamelCase__( self ): '''simple docstring''' __A : Union[str, Any] = XLMTokenizer(self.vocab_file , self.merges_file ) __A : Optional[Any] = '''lower''' __A : Any = ['''low''', '''er</w>'''] __A : Tuple = tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) __A : str = tokens + ['''<unk>'''] __A : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) @slow def UpperCamelCase__( self ): '''simple docstring''' __A : Optional[int] = XLMTokenizer.from_pretrained('''xlm-mlm-en-2048''' ) __A : Union[str, Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__lowerCamelCase ) __A : int = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__lowerCamelCase ) __A : int = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ) __A : List[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase , __lowerCamelCase ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
291
0
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _lowercase: Optional[int] = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex _lowercase: Dict = 10 _lowercase: Optional[Any] = 256 def a( A : List[str] ) -> Optional[MinHash]: """simple docstring""" if len(A ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=A ) for token in set(A ): min_hash.update(token.encode() ) return min_hash def a( A : str ) -> Set[str]: """simple docstring""" return {t for t in NON_ALPHA.split(A ) if len(t.strip() ) > 0} class _lowercase : """simple docstring""" def __init__(self , *, lowerCamelCase_ = 0.85 , ): """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(lowerCamelCase_ ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" a = self._index.query(lowerCamelCase_ ) if code_key in self._index.keys: print(F'''Duplicate key {code_key}''' ) return self._index.insert(lowerCamelCase_ , lowerCamelCase_ ) if len(lowerCamelCase_ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(lowerCamelCase_ ) break else: self._duplicate_clusters[close_duplicates[0]].add(lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(lowerCamelCase_ ) # reformat the cluster to be a list of dict a = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(lowerCamelCase_ ) return duplicate_clusters def UpperCamelCase_ (self , lowerCamelCase_ ): """simple docstring""" a = self.get_duplicate_clusters() with open(lowerCamelCase_ , "w" ) as f: json.dump(lowerCamelCase_ , lowerCamelCase_ ) def a( A : Any ) -> List[Any]: """simple docstring""" a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def a( A : Type[Dataset] ) -> List[Any]: """simple docstring""" with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(A , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def a( A : Type[Dataset] , A : float ) -> Dict: """simple docstring""" a = DuplicationIndex(duplication_jaccard_threshold=A ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(A ) ) , max_queue_size=100 ) ): di.add(A , A ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def a( A : str , A : str ) -> float: """simple docstring""" a = get_tokens(A ) a = get_tokens(A ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _lowercase: int = None def a( A : str , A : Tuple ) -> int: """simple docstring""" a = [] for elementa in cluster: a = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: a = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(A , A ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(A ) return extremes def a( A : str , A : List[str] , A : int ) -> Tuple: """simple docstring""" global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=A ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( A , A , ) , total=len(A ) , ): extremes_list.append(A ) return extremes_list def a( A : Type[Dataset] , A : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: """simple docstring""" a = make_duplicate_clusters(A , A ) a = {x["base_index"] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(A , A , A ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda A , A : idx not in remove_indices , with_indices=A ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element["base_index"] in extreme_dict if element["is_extreme"]: a = extreme_dict[element["base_index"]]["copies"] print(f'''Original dataset size: {len(A )}''' ) print(f'''Number of duplicate clusters: {len(A )}''' ) print(f'''Files in duplicate cluster: {len(A )}''' ) print(f'''Unique files in duplicate cluster: {len(A )}''' ) print(f'''Filtered dataset size: {len(A )}''' ) return ds_filter, duplicate_clusters
227
import random def a( A : Optional[Any] , A : Optional[Any] , A : str ) -> List[Any]: """simple docstring""" a = a[left_index] a = left_index + 1 for j in range(left_index + 1 , A ): if a[j] < pivot: a , a = a[i], a[j] i += 1 a , a = a[i - 1], a[left_index] return i - 1 def a( A : List[Any] , A : List[Any] , A : Union[str, Any] ) -> List[Any]: """simple docstring""" if left < right: a = random.randint(A , right - 1 ) a , a = ( a[left], a[pivot], ) # switches the pivot with the left most bound a = partition(A , A , A ) quick_sort_random( A , A , A ) # recursive quicksort to the left of the pivot point quick_sort_random( A , pivot_index + 1 , A ) # recursive quicksort to the right of the pivot point def a( ) -> Any: """simple docstring""" a = input("Enter numbers separated by a comma:\n" ).strip() a = [int(A ) for item in user_input.split("," )] quick_sort_random(A , 0 , len(A ) ) print(A ) if __name__ == "__main__": main()
227
1
def __lowercase ( __lowerCAmelCase : int ): if length <= 0 or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('Length must be a positive integer.' ) return [n * (2 * n - 1) for n in range(__lowerCAmelCase )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
109
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 rescale, resize, to_channel_dimension_format from ...image_utils import ( 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 snake_case : str = logging.get_logger(__name__) def __lowercase ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] ): a__ = b.T a__ = np.sum(np.square(__lowerCAmelCase ) , axis=1 ) a__ = np.sum(np.square(__lowerCAmelCase ) , axis=0 ) a__ = np.matmul(__lowerCAmelCase , __lowerCAmelCase ) a__ = aa[:, None] - 2 * ab + ba[None, :] return d def __lowercase ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : str ): a__ = x.reshape(-1 , 3 ) a__ = squared_euclidean_distance(__lowerCAmelCase , __lowerCAmelCase ) return np.argmin(__lowerCAmelCase , axis=1 ) class snake_case_ (lowerCamelCase_ ): UpperCAmelCase__ : Optional[Any] = ['''pixel_values'''] def __init__( self :Dict ,__snake_case :Optional[Union[List[List[int]], np.ndarray]] = None ,__snake_case :bool = True ,__snake_case :Dict[str, int] = None ,__snake_case :PILImageResampling = PILImageResampling.BILINEAR ,__snake_case :bool = True ,__snake_case :bool = True ,**__snake_case :Optional[int] ,) -> None: super().__init__(**__snake_case ) a__ = size if size is not None else {'height': 2_56, 'width': 2_56} a__ = get_size_dict(__snake_case ) a__ = np.array(__snake_case ) if clusters is not None else None a__ = do_resize a__ = size a__ = resample a__ = do_normalize a__ = do_color_quantize def lowerCamelCase__( self :Union[str, Any] ,__snake_case :np.ndarray ,__snake_case :Dict[str, int] ,__snake_case :PILImageResampling = PILImageResampling.BILINEAR ,__snake_case :Optional[Union[str, ChannelDimension]] = None ,**__snake_case :Any ,) -> np.ndarray: a__ = get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(F'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( __snake_case ,size=(size['height'], size['width']) ,resample=__snake_case ,data_format=__snake_case ,**__snake_case ) def lowerCamelCase__( self :List[Any] ,__snake_case :np.ndarray ,__snake_case :Optional[Union[str, ChannelDimension]] = None ,) -> np.ndarray: a__ = rescale(image=__snake_case ,scale=1 / 1_27.5 ,data_format=__snake_case ) a__ = image - 1 return image def lowerCamelCase__( self :Optional[Any] ,__snake_case :ImageInput ,__snake_case :bool = None ,__snake_case :Dict[str, int] = None ,__snake_case :PILImageResampling = None ,__snake_case :bool = None ,__snake_case :Optional[bool] = None ,__snake_case :Optional[Union[List[List[int]], np.ndarray]] = None ,__snake_case :Optional[Union[str, TensorType]] = None ,__snake_case :Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST ,**__snake_case :List[str] ,) -> PIL.Image.Image: a__ = do_resize if do_resize is not None else self.do_resize a__ = size if size is not None else self.size a__ = get_size_dict(__snake_case ) a__ = resample if resample is not None else self.resample a__ = do_normalize if do_normalize is not None else self.do_normalize a__ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize a__ = clusters if clusters is not None else self.clusters a__ = np.array(__snake_case ) a__ = make_list_of_images(__snake_case ) if not valid_images(__snake_case ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. a__ = [to_numpy_array(__snake_case ) for image in images] if do_resize: a__ = [self.resize(image=__snake_case ,size=__snake_case ,resample=__snake_case ) for image in images] if do_normalize: a__ = [self.normalize(image=__snake_case ) for image in images] if do_color_quantize: a__ = [to_channel_dimension_format(__snake_case ,ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) a__ = np.array(__snake_case ) a__ = color_quantize(__snake_case ,__snake_case ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) a__ = images.shape[0] a__ = images.reshape(__snake_case ,-1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. a__ = list(__snake_case ) else: a__ = [to_channel_dimension_format(__snake_case ,__snake_case ) for image in images] a__ = {'input_ids': images} return BatchFeature(data=__snake_case ,tensor_type=__snake_case )
109
1
def a ( snake_case__: str , snake_case__: str ): '''simple docstring''' lowercase_ = len(snake_case__ ) lowercase_ = len(snake_case__ ) lowercase_ = ( first_str_length if first_str_length > second_str_length else second_str_length ) lowercase_ = [] for char_count in range(snake_case__ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(snake_case__ ) if __name__ == "__main__": print(alternative_string_arrange('AB', 'XYZ'), end=' ')
30
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) _A = { """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": 10_00, """block_out_channels""": [32, 64], """attention_head_dim""": 8, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 64, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 3, """num_class_embeds""": 10_00, """block_out_channels""": [1_92, 1_92 * 2, 1_92 * 3, 1_92 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 2_56, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": None, """block_out_channels""": [2_56, 2_56, 2_56 * 2, 2_56 * 2, 2_56 * 4, 2_56 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """default""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """num_train_timesteps""": 40, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 2_01, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 1_51, """sigma_min""": 0.002, """sigma_max""": 80.0, } def a__ ( lowerCAmelCase ) -> Tuple: if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("""boolean value expected""" ) def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ) -> List[str]: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] UpperCAmelCase__ : Optional[Any] = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] UpperCAmelCase__ : Union[str, Any] = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.skip_connection.weight"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=None ) -> Optional[int]: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.norm.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.norm.bias"""] UpperCAmelCase__ : Union[str, Any] = weight_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Optional[Any] = bias_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = weight_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Dict = weight_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase ) -> str: UpperCAmelCase__ : Optional[Any] = torch.load(lowerCAmelCase , map_location="""cpu""" ) UpperCAmelCase__ : List[Any] = {} UpperCAmelCase__ : List[Any] = checkpoint["""time_embed.0.weight"""] UpperCAmelCase__ : str = checkpoint["""time_embed.0.bias"""] UpperCAmelCase__ : List[str] = checkpoint["""time_embed.2.weight"""] UpperCAmelCase__ : Dict = checkpoint["""time_embed.2.bias"""] if unet_config["num_class_embeds"] is not None: UpperCAmelCase__ : Dict = checkpoint["""label_emb.weight"""] UpperCAmelCase__ : str = checkpoint["""input_blocks.0.0.weight"""] UpperCAmelCase__ : List[str] = checkpoint["""input_blocks.0.0.bias"""] UpperCAmelCase__ : List[str] = unet_config["""down_block_types"""] UpperCAmelCase__ : Tuple = unet_config["""layers_per_block"""] UpperCAmelCase__ : int = unet_config["""attention_head_dim"""] UpperCAmelCase__ : Union[str, Any] = unet_config["""block_out_channels"""] UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Union[str, Any] = channels_list[0] for i, layer_type in enumerate(lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = channels_list[i] UpperCAmelCase__ : int = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Tuple = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : List[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Optional[Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Any = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : int = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Dict = F"""down_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : int = F"""input_blocks.{current_layer}.1""" UpperCAmelCase__ : Union[str, Any] = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : Any = F"""down_blocks.{i}.downsamplers.0""" UpperCAmelCase__ : List[str] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Tuple = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 UpperCAmelCase__ : Tuple = current_channels # hardcoded the mid-block for now UpperCAmelCase__ : List[Any] = """mid_block.resnets.0""" UpperCAmelCase__ : str = """middle_block.0""" UpperCAmelCase__ : List[str] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[str] = """mid_block.attentions.0""" UpperCAmelCase__ : Any = """middle_block.1""" UpperCAmelCase__ : Optional[int] = convert_attention(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[Any] = """mid_block.resnets.1""" UpperCAmelCase__ : Tuple = """middle_block.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Dict = unet_config["""up_block_types"""] for i, layer_type in enumerate(lowerCAmelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : Tuple = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : Any = F"""output_blocks.{current_layer-1}.1""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Dict = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Any = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = F"""up_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : List[str] = F"""output_blocks.{current_layer}.1""" UpperCAmelCase__ : Dict = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : int = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : int = F"""output_blocks.{current_layer-1}.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = checkpoint["""out.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint["""out.0.bias"""] UpperCAmelCase__ : Tuple = checkpoint["""out.2.weight"""] UpperCAmelCase__ : Optional[Any] = checkpoint["""out.2.bias"""] return new_checkpoint if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""") parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model.""" ) parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""") _A = parser.parse_args() _A = strabool(args.class_cond) _A = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: _A = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: _A = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: _A = None _A = con_pt_to_diffuser(args.unet_path, unet_config) _A = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: _A = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: _A = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') _A = CMStochasticIterativeScheduler(**scheduler_config) _A = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
171
0
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( _lowercase : int ) ->list[list[int]]: '''simple docstring''' a : List[Any] = [] if len(_lowerCamelCase ) == 1: return [nums.copy()] for _ in range(len(_lowerCamelCase ) ): a : int = nums.pop(0 ) a : Optional[int] = permute(_lowerCamelCase ) for perm in permutations: perm.append(_lowerCamelCase ) result.extend(_lowerCamelCase ) nums.append(_lowerCamelCase ) return result def _SCREAMING_SNAKE_CASE ( _lowercase : str ) ->Optional[int]: '''simple docstring''' def backtrack(_lowercase : Dict ): if start == len(_lowerCamelCase ) - 1: output.append(nums[:] ) else: for i in range(_lowerCamelCase , len(_lowerCamelCase ) ): a : Tuple = nums[i], nums[start] backtrack(start + 1 ) a : Any = nums[i], nums[start] # backtrack a : str = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function a : Union[str, Any] = permutea([1, 2, 3]) print(res) doctest.testmod()
363
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a : Optional[int] = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''', } class __UpperCamelCase ( a__ ): lowerCamelCase : Union[str, Any] ="""albert""" def __init__( self , lowerCAmelCase__=3_0000 , lowerCAmelCase__=128 , lowerCAmelCase__=4096 , lowerCAmelCase__=12 , lowerCAmelCase__=1 , lowerCAmelCase__=64 , lowerCAmelCase__=1_6384 , lowerCAmelCase__=1 , lowerCAmelCase__="gelu_new" , lowerCAmelCase__=0 , lowerCAmelCase__=0 , lowerCAmelCase__=512 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0.1 , lowerCAmelCase__="absolute" , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=3 , **lowerCAmelCase__ , ) -> List[str]: super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a : str = vocab_size a : Optional[Any] = embedding_size a : List[str] = hidden_size a : Optional[int] = num_hidden_layers a : Optional[Any] = num_hidden_groups a : str = num_attention_heads a : Optional[int] = inner_group_num a : List[Any] = hidden_act a : str = intermediate_size a : List[Any] = hidden_dropout_prob a : int = attention_probs_dropout_prob a : Tuple = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : int = layer_norm_eps a : List[str] = classifier_dropout_prob a : int = position_embedding_type class __UpperCamelCase ( a__ ): @property def __a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a : str = {0: "batch", 1: "choice", 2: "sequence"} else: a : Optional[Any] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
79
0
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Any =(DDPMParallelScheduler,) def snake_case ( self , **__a ): __lowerCAmelCase = { "num_train_timesteps": 10_00, "beta_start": 0.0_0_0_1, "beta_end": 0.0_2, "beta_schedule": "linear", "variance_type": "fixed_small", "clip_sample": True, } config.update(**__a ) return config def snake_case ( self ): for timesteps in [1, 5, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def snake_case ( self ): for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def snake_case ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def snake_case ( self ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=__a ) def snake_case ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def snake_case ( self ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def snake_case ( self ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def snake_case ( self ): for t in [0, 5_00, 9_99]: self.check_over_forward(time_step=__a ) def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 ) - 0.0_0_9_7_9 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 ) - 0.0_2 ) ) < 1e-5 def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = len(__a ) __lowerCAmelCase = self.dummy_model() __lowerCAmelCase = self.dummy_sample_deter __lowerCAmelCase = self.dummy_sample_deter + 0.1 __lowerCAmelCase = self.dummy_sample_deter - 0.1 __lowerCAmelCase = samplea.shape[0] __lowerCAmelCase = torch.stack([samplea, samplea, samplea] , dim=0 ) __lowerCAmelCase = torch.arange(__a )[0:3, None].repeat(1 , __a ) __lowerCAmelCase = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __lowerCAmelCase = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) __lowerCAmelCase = torch.sum(torch.abs(__a ) ) __lowerCAmelCase = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_1_5_3.1_8_3_3 ) < 1e-2 assert abs(result_mean.item() - 0.5_0_0_5 ) < 1e-3 def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = len(__a ) __lowerCAmelCase = self.dummy_model() __lowerCAmelCase = self.dummy_sample_deter __lowerCAmelCase = torch.manual_seed(0 ) for t in reversed(range(__a ) ): # 1. predict noise residual __lowerCAmelCase = model(__a , __a ) # 2. predict previous mean of sample x_t-1 __lowerCAmelCase = scheduler.step(__a , __a , __a , generator=__a ).prev_sample __lowerCAmelCase = pred_prev_sample __lowerCAmelCase = torch.sum(torch.abs(__a ) ) __lowerCAmelCase = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 2_5_8.9_6_0_6 ) < 1e-2 assert abs(result_mean.item() - 0.3_3_7_2 ) < 1e-3 def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config(prediction_type="v_prediction" ) __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = len(__a ) __lowerCAmelCase = self.dummy_model() __lowerCAmelCase = self.dummy_sample_deter __lowerCAmelCase = torch.manual_seed(0 ) for t in reversed(range(__a ) ): # 1. predict noise residual __lowerCAmelCase = model(__a , __a ) # 2. predict previous mean of sample x_t-1 __lowerCAmelCase = scheduler.step(__a , __a , __a , generator=__a ).prev_sample __lowerCAmelCase = pred_prev_sample __lowerCAmelCase = torch.sum(torch.abs(__a ) ) __lowerCAmelCase = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 2_0_2.0_2_9_6 ) < 1e-2 assert abs(result_mean.item() - 0.2_6_3_1 ) < 1e-3 def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = [1_00, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=__a ) __lowerCAmelCase = scheduler.timesteps for i, timestep in enumerate(__a ): if i == len(__a ) - 1: __lowerCAmelCase = -1 else: __lowerCAmelCase = timesteps[i + 1] __lowerCAmelCase = scheduler.previous_timestep(__a ) __lowerCAmelCase = prev_t.item() self.assertEqual(__a , __a ) def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = [1_00, 87, 50, 51, 0] with self.assertRaises(__a , msg="`custom_timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = [1_00, 87, 50, 1, 0] __lowerCAmelCase = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `custom_timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def snake_case ( self ): __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**__a ) __lowerCAmelCase = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
57
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = 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 , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = 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 ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
1
"""simple docstring""" from torch import nn class __snake_case ( nn.Module): def __init__( self : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : str ): """simple docstring""" super().__init__() _lowerCamelCase : List[str] = class_size _lowerCamelCase : List[str] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) _lowerCamelCase : Optional[int] = nn.Linear(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.mlp(__lowerCAmelCase ) return logits
175
"""simple docstring""" 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 lowerCAmelCase__ = logging.get_logger(__name__) logging.set_verbosity_info() def snake_case_ ( A_ : str, A_ : str ): '''simple docstring''' if "xprophetnet" in prophetnet_checkpoint_path: _lowerCamelCase : Any = XLMProphetNetForConditionalGenerationOld.from_pretrained(A_ ) _lowerCamelCase , _lowerCamelCase : List[str] = XLMProphetNetForConditionalGeneration.from_pretrained( A_, output_loading_info=A_ ) else: _lowerCamelCase : str = ProphetNetForConditionalGenerationOld.from_pretrained(A_ ) _lowerCamelCase , _lowerCamelCase : Any = ProphetNetForConditionalGeneration.from_pretrained( A_, output_loading_info=A_ ) _lowerCamelCase : Optional[Any] = ['''key_proj''', '''value_proj''', '''query_proj'''] _lowerCamelCase : List[Any] = { '''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"]: _lowerCamelCase : Union[str, Any] = key.split('''.''' ) if attributes[0] == "lm_head": _lowerCamelCase : str = prophet _lowerCamelCase : List[Any] = prophet_old else: _lowerCamelCase : Optional[int] = prophet.prophetnet _lowerCamelCase : Optional[Any] = prophet_old.model _lowerCamelCase : Any = False for attribute in attributes: if attribute in mapping: _lowerCamelCase : Optional[int] = mapping[attribute] if not hasattr(A_, A_ ) and len(A_ ) > 0: _lowerCamelCase : int = attribute elif hasattr(A_, A_ ): _lowerCamelCase : int = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" _lowerCamelCase : Optional[int] = old_model.weight logger.info(F'''{attribute} is initialized.''' ) _lowerCamelCase : List[str] = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" _lowerCamelCase : int = old_model.bias logger.info(F'''{attribute} is initialized''' ) _lowerCamelCase : Union[str, Any] = True break elif attribute in special_keys and hasattr(A_, '''in_proj_weight''' ): _lowerCamelCase : Tuple = old_model.in_proj_weight.shape[0] // 3 _lowerCamelCase : List[Any] = getattr(A_, A_ ) 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": _lowerCamelCase : Optional[Any] = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) _lowerCamelCase : int = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": _lowerCamelCase : int = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) _lowerCamelCase : str = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": _lowerCamelCase : Tuple = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) _lowerCamelCase : str = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) _lowerCamelCase : Dict = 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_12, "We want 512 position_embeddings." _lowerCamelCase : List[str] = nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) _lowerCamelCase : Optional[Any] = True break if attribute.isdigit(): _lowerCamelCase : Optional[int] = model[int(A_ )] _lowerCamelCase : List[Any] = old_model[int(A_ )] else: _lowerCamelCase : List[str] = getattr(A_, A_ ) if old_attribute == "": _lowerCamelCase : str = old_model else: if not hasattr(A_, A_ ): raise ValueError(F'''{old_model} does not have {old_attribute}''' ) _lowerCamelCase : Optional[int] = getattr(A_, A_ ) 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(A_ ) if __name__ == "__main__": lowerCAmelCase__ = 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.''' ) lowerCAmelCase__ = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
175
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __a = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST', 'UniSpeechForCTC', 'UniSpeechForPreTraining', 'UniSpeechForSequenceClassification', 'UniSpeechModel', 'UniSpeechPreTrainedModel', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
30
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def a ( snake_case__: int , snake_case__: Tuple , snake_case__: Dict , snake_case__: Dict , snake_case__: List[Any] , snake_case__: int , snake_case__: List[Any] , snake_case__: Optional[int] , snake_case__: str , snake_case__: Union[str, Any] , snake_case__: List[str] , snake_case__: int , ): '''simple docstring''' lowercase_ = { '''7z''': (seven_zip_file, SevenZipExtractor), '''bz2''': (bza_file, BzipaExtractor), '''gzip''': (gz_file, GzipExtractor), '''lz4''': (lza_file, LzaExtractor), '''tar''': (tar_file, TarExtractor), '''xz''': (xz_file, XzExtractor), '''zip''': (zip_file, ZipExtractor), '''zstd''': (zstd_file, ZstdExtractor), } lowercase_ , lowercase_ = input_paths_and_base_extractors[compression_format] if input_path is None: lowercase_ = F'''for \'{compression_format}\' compression_format, ''' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(snake_case__ ) assert base_extractor.is_extractable(snake_case__ ) lowercase_ = tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') base_extractor.extract(snake_case__ , snake_case__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name lowercase_ = file_path.read_text(encoding='''utf-8''' ) else: lowercase_ = output_path.read_text(encoding='''utf-8''' ) lowercase_ = text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def a ( snake_case__: List[Any] , snake_case__: int , snake_case__: Optional[int] , snake_case__: Union[str, Any] , snake_case__: List[Any] , snake_case__: Tuple , snake_case__: Optional[int] , snake_case__: List[str] , snake_case__: Union[str, Any] , snake_case__: Tuple , snake_case__: int , snake_case__: Optional[int] , ): '''simple docstring''' lowercase_ = { '''7z''': seven_zip_file, '''bz2''': bza_file, '''gzip''': gz_file, '''lz4''': lza_file, '''tar''': tar_file, '''xz''': xz_file, '''zip''': zip_file, '''zstd''': zstd_file, } lowercase_ = input_paths[compression_format] if input_path is None: lowercase_ = F'''for \'{compression_format}\' compression_format, ''' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(snake_case__ ) lowercase_ = Extractor.infer_extractor_format(snake_case__ ) assert extractor_format is not None lowercase_ = tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') Extractor.extract(snake_case__ , snake_case__ , snake_case__ ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name lowercase_ = file_path.read_text(encoding='''utf-8''' ) else: lowercase_ = output_path.read_text(encoding='''utf-8''' ) lowercase_ = text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.fixture def a ( snake_case__: Union[str, Any] , snake_case__: List[Any] ): '''simple docstring''' import tarfile lowercase_ = tmp_path / '''data_dot_dot''' directory.mkdir() lowercase_ = directory / '''tar_file_with_dot_dot.tar''' with tarfile.TarFile(snake_case__ , '''w''' ) as f: f.add(snake_case__ , arcname=os.path.join('''..''' , text_file.name ) ) return path @pytest.fixture def a ( snake_case__: int ): '''simple docstring''' import tarfile lowercase_ = tmp_path / '''data_sym_link''' directory.mkdir() lowercase_ = directory / '''tar_file_with_sym_link.tar''' os.symlink('''..''' , directory / '''subdir''' , target_is_directory=snake_case__ ) with tarfile.TarFile(snake_case__ , '''w''' ) as f: f.add(str(directory / '''subdir''' ) , arcname='''subdir''' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( '''insecure_tar_file, error_log''' , [('''tar_file_with_dot_dot''', '''illegal path'''), ('''tar_file_with_sym_link''', '''Symlink''')] , ) def a ( snake_case__: List[Any] , snake_case__: Optional[int] , snake_case__: List[str] , snake_case__: List[str] , snake_case__: int , snake_case__: Optional[Any] ): '''simple docstring''' lowercase_ = { '''tar_file_with_dot_dot''': tar_file_with_dot_dot, '''tar_file_with_sym_link''': tar_file_with_sym_link, } lowercase_ = insecure_tar_files[insecure_tar_file] lowercase_ = tmp_path / '''extracted''' TarExtractor.extract(snake_case__ , snake_case__ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def a ( snake_case__: Optional[int] ): '''simple docstring''' # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number lowercase_ = tmpdir / '''not_a_zip_file''' # From: https://github.com/python/cpython/pull/5053 lowercase_ = ( B'''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00''' B'''\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I''' B'''DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07''' B'''\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82''' ) with not_a_zip_file.open('''wb''' ) as f: f.write(snake_case__ ) assert zipfile.is_zipfile(str(snake_case__ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(snake_case__ ) # but we're right
30
1
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 _lowercase: Optional[int] = get_tests_dir("fixtures/dummy-config.json") class _lowercase ( unittest.TestCase ): """simple docstring""" def UpperCamelCase_ (self ): """simple docstring""" a = 0 def UpperCamelCase_ (self ): """simple docstring""" self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto" ) ) def UpperCamelCase_ (self ): """simple docstring""" a = AutoConfig.from_pretrained("bert-base-uncased" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = AutoConfig.for_model("roberta" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. a = os.path.join(lowerCamelCase_ , "fake-roberta" ) os.makedirs(lowerCamelCase_ , exist_ok=lowerCamelCase_ ) with open(os.path.join(lowerCamelCase_ , "config.json" ) , "w" ) as f: f.write(json.dumps({} ) ) a = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(type(lowerCamelCase_ ) , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" try: AutoConfig.register("custom" , lowerCamelCase_ ) # Wrong model type will raise an error with self.assertRaises(lowerCamelCase_ ): AutoConfig.register("model" , lowerCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoConfig.register("bert" , lowerCamelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API a = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase_ ) a = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def UpperCamelCase_ (self ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , "bert-base is not a local folder and is not a valid model identifier" ): a = AutoConfig.from_pretrained("bert-base" ) def UpperCamelCase_ (self ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): a = AutoConfig.from_pretrained(lowerCamelCase_ , revision="aaaaaa" ) def UpperCamelCase_ (self ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json." , ): a = AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo" ) def UpperCamelCase_ (self ): """simple docstring""" with self.assertRaises(lowerCamelCase_ ): a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase_ ): a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCamelCase_ ) a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase_ ) a = AutoConfig.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ ) self.assertEqual(reloaded_config.__class__.__name__ , "NewModelConfig" ) def UpperCamelCase_ (self ): """simple docstring""" class _lowercase ( lowerCAmelCase ): """simple docstring""" __A = "new-model" try: AutoConfig.register("new-model" , lowerCamelCase_ ) # If remote code is not set, the default is to use local a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote code is disabled, we load the local one. a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote is enabled, we load from the Hub a = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
71
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase: str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _lowercase ( lowerCAmelCase, unittest.TestCase ): """simple docstring""" __A = XLMProphetNetTokenizer __A = False __A = True def UpperCamelCase_ (self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing a = XLMProphetNetTokenizer(lowerCamelCase_ , keep_accents=lowerCamelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ (self ): """simple docstring""" a = "[PAD]" a = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase_ ) , lowerCamelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase_ ) , lowerCamelCase_ ) def UpperCamelCase_ (self ): """simple docstring""" a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "[PAD]" ) self.assertEqual(vocab_keys[1] , "[CLS]" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(lowerCamelCase_ ) , 1012 ) def UpperCamelCase_ (self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def UpperCamelCase_ (self ): """simple docstring""" a = XLMProphetNetTokenizer(lowerCamelCase_ , keep_accents=lowerCamelCase_ ) a = 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]] , ) a = 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", "é", ".", ] , ) a = tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) self.assertListEqual( lowerCamelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) a = 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]", ".", ] , ) @cached_property def UpperCamelCase_ (self ): """simple docstring""" return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased" ) @slow def UpperCamelCase_ (self ): """simple docstring""" a = "Hello World!" a = [35389, 6672, 49, 2] self.assertListEqual(lowerCamelCase_ , self.big_tokenizer.encode(lowerCamelCase_ ) ) @slow def UpperCamelCase_ (self ): """simple docstring""" a = {"input_ids": [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
71
1
"""simple docstring""" from collections import deque def UpperCAmelCase ( UpperCAmelCase ) -> int: snake_case_ = len(UpperCAmelCase ) snake_case_ = deque() snake_case_ = [False for _ in range(UpperCAmelCase )] snake_case_ = [-1 for _ in range(UpperCAmelCase )] snake_case_ = index_of[:] def strong_connect(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): snake_case_ = index # the number when this node is seen snake_case_ = index # lowest rank node reachable from here index += 1 stack.append(UpperCAmelCase ) snake_case_ = True for w in g[v]: if index_of[w] == -1: snake_case_ = strong_connect(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) snake_case_ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: snake_case_ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: snake_case_ = [] snake_case_ = stack.pop() snake_case_ = False component.append(UpperCAmelCase ) while w != v: snake_case_ = stack.pop() snake_case_ = False component.append(UpperCAmelCase ) components.append(UpperCAmelCase ) return index snake_case_ = [] for v in range(UpperCAmelCase ): if index_of[v] == -1: strong_connect(UpperCAmelCase , 0 , UpperCAmelCase ) return components def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> Optional[int]: snake_case_ = [[] for _ in range(UpperCAmelCase )] for u, v in edges: g[u].append(UpperCAmelCase ) return g if __name__ == "__main__": # Test __UpperCamelCase = 7 __UpperCamelCase = [0, 0, 1, 2, 3, 3, 4, 4, 6] __UpperCamelCase = [1, 3, 2, 0, 1, 4, 5, 6, 5] __UpperCamelCase = [(u, v) for u, v in zip(source, target)] __UpperCamelCase = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
69
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = '''▁''' __UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model'''} __UpperCamelCase = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model''' ), } } __UpperCamelCase = { '''facebook/nllb-200-distilled-600M''': 1024, } # fmt: off __UpperCamelCase = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = ["input_ids", "attention_mask"] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] def __init__( self, lowerCAmelCase__, lowerCAmelCase__="<s>", lowerCAmelCase__="</s>", lowerCAmelCase__="</s>", lowerCAmelCase__="<s>", lowerCAmelCase__="<unk>", lowerCAmelCase__="<pad>", lowerCAmelCase__="<mask>", lowerCAmelCase__=None, lowerCAmelCase__=None, lowerCAmelCase__=None, lowerCAmelCase__ = None, lowerCAmelCase__=None, lowerCAmelCase__=False, **lowerCAmelCase__, ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it snake_case_ = AddedToken(lowerCAmelCase__, lstrip=lowerCAmelCase__, rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__, lowerCAmelCase__) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs snake_case_ = legacy_behaviour super().__init__( bos_token=lowerCAmelCase__, eos_token=lowerCAmelCase__, unk_token=lowerCAmelCase__, sep_token=lowerCAmelCase__, cls_token=lowerCAmelCase__, pad_token=lowerCAmelCase__, mask_token=lowerCAmelCase__, tokenizer_file=lowerCAmelCase__, src_lang=lowerCAmelCase__, tgt_lang=lowerCAmelCase__, additional_special_tokens=lowerCAmelCase__, sp_model_kwargs=self.sp_model_kwargs, legacy_behaviour=lowerCAmelCase__, **lowerCAmelCase__, ) snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowerCAmelCase__)) snake_case_ = 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>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token snake_case_ = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case_ = 1 snake_case_ = len(self.sp_model) snake_case_ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(lowerCAmelCase__) } snake_case_ = {v: k for k, v in self.lang_code_to_id.items()} snake_case_ = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} snake_case_ = list(self.lang_code_to_id.keys()) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens]) snake_case_ = src_lang if src_lang is not None else 'eng_Latn' snake_case_ = self.lang_code_to_id[self._src_lang] snake_case_ = tgt_lang self.set_src_lang_special_tokens(self._src_lang) def __getstate__( self) -> Union[str, Any]: snake_case_ = self.__dict__.copy() snake_case_ = None snake_case_ = self.sp_model.serialized_model_proto() return state def __setstate__( self, lowerCAmelCase__) -> Tuple: snake_case_ = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs'): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) @property def a_ ( self) -> str: return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def a_ ( self) -> str: return self._src_lang @src_lang.setter def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None, lowerCAmelCase__ = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase__, token_ids_a=lowerCAmelCase__, already_has_special_tokens=lowerCAmelCase__) snake_case_ = [1] * len(self.prefix_tokens) snake_case_ = [1] * len(self.suffix_tokens) if token_ids_a is None: return prefix_ones + ([0] * len(lowerCAmelCase__)) + suffix_ones return prefix_ones + ([0] * len(lowerCAmelCase__)) + ([0] * len(lowerCAmelCase__)) + suffix_ones def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> List[int]: 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 a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> List[int]: 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 + sep + token_ids_a + sep) * [0] def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, **lowerCAmelCase__) -> str: if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model') snake_case_ = src_lang snake_case_ = self(lowerCAmelCase__, add_special_tokens=lowerCAmelCase__, return_tensors=lowerCAmelCase__, **lowerCAmelCase__) snake_case_ = self.convert_tokens_to_ids(lowerCAmelCase__) snake_case_ = tgt_lang_id return inputs def a_ ( self) -> List[Any]: snake_case_ = {self.convert_ids_to_tokens(lowerCAmelCase__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def a_ ( self, lowerCAmelCase__) -> List[str]: return self.sp_model.encode(lowerCAmelCase__, out_type=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> Any: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case_ = self.sp_model.PieceToId(lowerCAmelCase__) # 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 a_ ( self, lowerCAmelCase__) -> Dict: 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 a_ ( self, lowerCAmelCase__) -> List[str]: snake_case_ = ''.join(lowerCAmelCase__).replace(lowerCAmelCase__, ' ').strip() return out_string def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase__): logger.error(f'Vocabulary path ({save_directory}) should be a directory') return snake_case_ = os.path.join( lowerCAmelCase__, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCAmelCase__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, lowerCAmelCase__) elif not os.path.isfile(self.vocab_file): with open(lowerCAmelCase__, 'wb') as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase__) return (out_vocab_file,) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = "eng_Latn", lowerCAmelCase__ = None, lowerCAmelCase__ = "fra_Latn", **lowerCAmelCase__, ) -> BatchEncoding: snake_case_ = src_lang snake_case_ = tgt_lang return super().prepare_seqaseq_batch(lowerCAmelCase__, lowerCAmelCase__, **lowerCAmelCase__) def a_ ( self) -> Union[str, Any]: return self.set_src_lang_special_tokens(self.src_lang) def a_ ( self) -> int: return self.set_tgt_lang_special_tokens(self.tgt_lang) def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = self.lang_code_to_id[src_lang] if self.legacy_behaviour: snake_case_ = [] snake_case_ = [self.eos_token_id, self.cur_lang_code] else: snake_case_ = [self.cur_lang_code] snake_case_ = [self.eos_token_id] def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = self.lang_code_to_id[lang] if self.legacy_behaviour: snake_case_ = [] snake_case_ = [self.eos_token_id, self.cur_lang_code] else: snake_case_ = [self.cur_lang_code] snake_case_ = [self.eos_token_id]
69
1
from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): def __init__( self : Dict , lowerCamelCase_ : Distribution , lowerCamelCase_ : Union[str, Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Tuple=0 ): """simple docstring""" UpperCamelCase = 1.0 if scale is None else scale UpperCamelCase = 0.0 if loc is None else loc super().__init__(__UpperCAmelCase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=__UpperCAmelCase )] ) @property def lowerCamelCase_ ( self : Any ): """simple docstring""" return self.base_dist.mean * self.scale + self.loc @property def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" return self.base_dist.variance * self.scale**2 @property def lowerCamelCase_ ( self : Dict ): """simple docstring""" return self.variance.sqrt() class SCREAMING_SNAKE_CASE_ ( nn.Module ): def __init__( self : List[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : Callable[..., Tuple[torch.Tensor]] , **lowerCamelCase_ : Union[str, Any] ): """simple docstring""" super().__init__(**__UpperCAmelCase ) UpperCamelCase = args_dim UpperCamelCase = nn.ModuleList([nn.Linear(__UpperCAmelCase , __UpperCAmelCase ) for dim in args_dim.values()] ) UpperCamelCase = domain_map def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : torch.Tensor ): """simple docstring""" UpperCamelCase = [proj(__UpperCAmelCase ) for proj in self.proj] return self.domain_map(*__UpperCAmelCase ) class SCREAMING_SNAKE_CASE_ ( nn.Module ): def __init__( self : Union[str, Any] , lowerCamelCase_ : Tuple ): """simple docstring""" super().__init__() UpperCamelCase = function def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : int , *lowerCamelCase_ : List[str] ): """simple docstring""" return self.function(__UpperCAmelCase , *__UpperCAmelCase ) class SCREAMING_SNAKE_CASE_ : __lowerCAmelCase = 42 __lowerCAmelCase = 42 __lowerCAmelCase = 42 def __init__( self : Optional[Any] , lowerCamelCase_ : int = 1 ): """simple docstring""" UpperCamelCase = dim UpperCamelCase = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[Any] ): """simple docstring""" if self.dim == 1: return self.distribution_class(*__UpperCAmelCase ) else: return Independent(self.distribution_class(*__UpperCAmelCase ) , 1 ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[torch.Tensor] = None , lowerCamelCase_ : Optional[torch.Tensor] = None , ): """simple docstring""" UpperCamelCase = self._base_distribution(__UpperCAmelCase ) if loc is None and scale is None: return distr else: return AffineTransformed(__UpperCAmelCase , loc=__UpperCAmelCase , scale=__UpperCAmelCase , event_dim=self.event_dim ) @property def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return () if self.dim == 1 else (self.dim,) @property def lowerCamelCase_ ( self : str ): """simple docstring""" return len(self.event_shape ) @property def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" return 0.0 def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : int ): """simple docstring""" return ParameterProjection( in_features=__UpperCAmelCase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCamelCase_ ( self : List[str] , *lowerCamelCase_ : torch.Tensor ): """simple docstring""" raise NotImplementedError() @staticmethod def lowerCamelCase_ ( lowerCamelCase_ : torch.Tensor ): """simple docstring""" return (x + torch.sqrt(torch.square(__UpperCAmelCase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = {"""df""": 1, """loc""": 1, """scale""": 1} __lowerCAmelCase = StudentT @classmethod def lowerCamelCase_ ( cls : Union[str, Any] , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : torch.Tensor ): """simple docstring""" UpperCamelCase = cls.squareplus(__UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) UpperCamelCase = 2.0 + cls.squareplus(__UpperCAmelCase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = {"""loc""": 1, """scale""": 1} __lowerCAmelCase = Normal @classmethod def lowerCamelCase_ ( cls : Dict , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : torch.Tensor ): """simple docstring""" UpperCamelCase = cls.squareplus(__UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = {"""total_count""": 1, """logits""": 1} __lowerCAmelCase = NegativeBinomial @classmethod def lowerCamelCase_ ( cls : Optional[int] , lowerCamelCase_ : torch.Tensor , lowerCamelCase_ : torch.Tensor ): """simple docstring""" UpperCamelCase = cls.squareplus(__UpperCAmelCase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Union[str, Any] ): """simple docstring""" UpperCamelCase , UpperCamelCase = distr_args if self.dim == 1: return self.distribution_class(total_count=__UpperCAmelCase , logits=__UpperCAmelCase ) else: return Independent(self.distribution_class(total_count=__UpperCAmelCase , logits=__UpperCAmelCase ) , 1 ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[torch.Tensor] = None , lowerCamelCase_ : Optional[torch.Tensor] = None ): """simple docstring""" UpperCamelCase , UpperCamelCase = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
354
import argparse _SCREAMING_SNAKE_CASE = """docs/source/_static/js/custom.js""" def lowercase( UpperCamelCase_ ) -> Union[str, Any]: '''simple docstring''' with open(UpperCamelCase_ , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCamelCase = f.readlines() UpperCamelCase = 0 # First let's put the right version while not lines[index].startswith("""const stableVersion =""" ): index += 1 UpperCamelCase = f"""const stableVersion = \"v{version}\"\n""" # Then update the dictionary while not lines[index].startswith("""const versionMapping = {""" ): index += 1 # We go until the end while not lines[index].startswith("""}""" ): index += 1 # We add the new version at the end lines[index - 1] += f""" \"v{version}\": \"v{version}\",\n""" with open(UpperCamelCase_ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase_ ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument("""--version""", help="""Release version.""") _SCREAMING_SNAKE_CASE = parser.parse_args() update_custom_js(args.version)
165
0
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : str , __lowercase : str , __lowercase : Dict=13 , __lowercase : Dict=7 , __lowercase : str=True , __lowercase : List[Any]=True , __lowercase : List[str]=True , __lowercase : List[str]=True , __lowercase : Any=99 , __lowercase : Dict=32 , __lowercase : Dict=5 , __lowercase : Union[str, Any]=4 , __lowercase : Any=37 , __lowercase : Union[str, Any]="gelu" , __lowercase : Dict=0.1 , __lowercase : Dict=0.1 , __lowercase : Optional[Any]=512 , __lowercase : Optional[int]=16 , __lowercase : str=2 , __lowercase : Optional[Any]=0.02 , __lowercase : Tuple=4 , ): '''simple docstring''' __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_attention_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_choices def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_attention_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[Any] =True __lowerCamelCase : Optional[int] =( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = FlaxRobertaModelTester(self ) @slow def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained("""roberta-base""" , from_pt=__lowercase ) __a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__lowercase )
302
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = Dict[str, Any] lowerCamelCase__ = List[Prediction] @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Tuple , *__lowercase : Tuple , **__lowercase : Optional[int] ): '''simple docstring''' super().__init__(*__lowercase , **__lowercase ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : List[str] ): '''simple docstring''' __a = {} if "threshold" in kwargs: __a = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : List[Any] , *__lowercase : Any , **__lowercase : Tuple ): '''simple docstring''' return super().__call__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tuple ): '''simple docstring''' __a = load_image(__lowercase ) __a = torch.IntTensor([[image.height, image.width]] ) __a = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: __a = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) __a = target_size return inputs def UpperCamelCase_ ( self : Dict , __lowercase : List[str] ): '''simple docstring''' __a = model_inputs.pop("""target_size""" ) __a = self.model(**__lowercase ) __a = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: __a = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any]=0.9 ): '''simple docstring''' __a = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __a , __a = target_size[0].tolist() def unnormalize(__lowercase : Optional[Any] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) __a , __a = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __a = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __a = [unnormalize(__lowercase ) for bbox in model_outputs["""bbox"""].squeeze(0 )] __a = ["""score""", """label""", """box"""] __a = [dict(zip(__lowercase , __lowercase ) ) for vals in zip(scores.tolist() , __lowercase , __lowercase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __a = self.image_processor.post_process_object_detection(__lowercase , __lowercase , __lowercase ) __a = raw_annotations[0] __a = raw_annotation["""scores"""] __a = raw_annotation["""labels"""] __a = raw_annotation["""boxes"""] __a = scores.tolist() __a = [self.model.config.idalabel[label.item()] for label in labels] __a = [self._get_bounding_box(__lowercase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __a = ["""score""", """label""", """box"""] __a = [ dict(zip(__lowercase , __lowercase ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCamelCase_ ( self : Optional[int] , __lowercase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) __a , __a , __a , __a = box.int().tolist() __a = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
302
1
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def lowercase ( _snake_case : str ) ->Optional[Any]: """simple docstring""" def decorator(_snake_case : List[str] ): __snake_case : str = getattr(_snake_case , '''handle_key''' , [] ) handle += [key] setattr(_snake_case , '''handle_key''' , _snake_case ) return func return decorator def lowercase ( *_snake_case : List[str] ) ->Dict: """simple docstring""" def decorator(_snake_case : int ): __snake_case : List[str] = getattr(_snake_case , '''handle_key''' , [] ) handle += keys setattr(_snake_case , '''handle_key''' , _snake_case ) return func return decorator class _UpperCAmelCase ( __snake_case ): '''simple docstring''' def __new__(cls , a_ , a_ , a_ ): '''simple docstring''' __snake_case : Optional[int] = super().__new__(cls , a_ , a_ , a_ ) if not hasattr(a_ , '''key_handler''' ): setattr(a_ , '''key_handler''' , {} ) setattr(a_ , '''handle_input''' , KeyHandler.handle_input ) for value in attrs.values(): __snake_case : Optional[int] = getattr(a_ , '''handle_key''' , [] ) for key in handled_keys: __snake_case : Tuple = value return new_cls @staticmethod def SCREAMING_SNAKE_CASE (cls ): '''simple docstring''' __snake_case : int = get_character() if char != KEYMAP["undefined"]: __snake_case : Optional[int] = ord(a_ ) __snake_case : List[Any] = cls.key_handler.get(a_ ) if handler: __snake_case : str = char return handler(cls ) else: return None def lowercase ( cls : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
24
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__(self , a_ , a_=7 , a_=3 , a_=18 , a_=30 , a_=4_00 , a_=True , a_=None , a_=True , a_=None , a_=True , ): '''simple docstring''' __snake_case : List[Any] = size if size is not None else {'''shortest_edge''': 20} __snake_case : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __snake_case : Tuple = parent __snake_case : Tuple = batch_size __snake_case : Tuple = num_channels __snake_case : List[str] = image_size __snake_case : Optional[Any] = min_resolution __snake_case : List[Any] = max_resolution __snake_case : List[Any] = do_resize __snake_case : Dict = size __snake_case : Dict = do_center_crop __snake_case : Dict = crop_size __snake_case : str = do_flip_channel_order def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class _UpperCAmelCase ( __snake_case, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =MobileViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Tuple = MobileViTImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , '''do_resize''' ) ) self.assertTrue(hasattr(a_ , '''size''' ) ) self.assertTrue(hasattr(a_ , '''do_center_crop''' ) ) self.assertTrue(hasattr(a_ , '''center_crop''' ) ) self.assertTrue(hasattr(a_ , '''do_flip_channel_order''' ) ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : Union[str, 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 __snake_case : Optional[int] = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __snake_case : str = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : int = 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 __snake_case : 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __snake_case : Union[str, 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : Any = 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 __snake_case : 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __snake_case : Tuple = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
24
1
from collections import defaultdict from math import gcd def a__ ( __UpperCamelCase = 1_5_0_0_0_0_0 ): SCREAMING_SNAKE_CASE_ = defaultdict(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , __UpperCamelCase , 2 ): if gcd(__UpperCamelCase , __UpperCamelCase ) > 1: continue SCREAMING_SNAKE_CASE_ = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(__UpperCamelCase , limit + 1 , __UpperCamelCase ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(f"{solution() = }")
118
def a__ ( __UpperCamelCase = 1_0_0_0 ): SCREAMING_SNAKE_CASE_ = -1 SCREAMING_SNAKE_CASE_ = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c SCREAMING_SNAKE_CASE_ = (n * n - 2 * a * n) // (2 * n - 2 * a) SCREAMING_SNAKE_CASE_ = n - a - b if c * c == (a * a + b * b): SCREAMING_SNAKE_CASE_ = a * b * c if candidate >= product: SCREAMING_SNAKE_CASE_ = candidate return product if __name__ == "__main__": print(f"{solution() = }")
118
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): _UpperCAmelCase : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _UpperCAmelCase : Tuple = 1_2_8_0_2_2 _UpperCAmelCase : Optional[int] = 1_2_8_0_2_8 @require_sentencepiece class a__ ( __A , unittest.TestCase ): """simple docstring""" __UpperCamelCase : List[Any] = MaMaaaTokenizer __UpperCamelCase : Dict = False __UpperCamelCase : Optional[Any] = False __UpperCamelCase : str = True def _snake_case (self ): super().setUp() __lowerCAmelCase = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] __lowerCAmelCase = dict(zip(__lowercase , range(len(__lowercase ) ) ) ) __lowerCAmelCase = Path(self.tmpdirname ) save_json(__lowercase , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__lowercase , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) __lowerCAmelCase = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case (self , **__lowercase ): return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def _snake_case (self , __lowercase ): return ( "This is a test", "This is a test", ) def _snake_case (self ): __lowerCAmelCase = '''</s>''' __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase ) , __lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase ) , __lowercase ) def _snake_case (self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(__lowercase ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def _snake_case (self ): pass def _snake_case (self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowercase ) , [2, 3, 4, 5, 6] , ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(__lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) __lowerCAmelCase = tokenizer.convert_tokens_to_string(__lowercase ) self.assertEqual(__lowercase , '''This is a test''' ) @slow def _snake_case (self ): # fmt: off __lowerCAmelCase = {'''input_ids''': [[12_80_22, 11_01_08, 3_97, 11, 3_82_72, 22_47, 12_48_11, 2_85, 1_81_05, 15_86, 2_07, 7, 3_95_34, 44_28, 3_97, 10_19, 1_81_05, 15_86, 2_07, 7, 4_13_37, 1_67_86, 2_41, 7, 2_02_14, 17, 12_56_90, 1_03_98, 7, 4_43_78, 5_80_69, 6_83_42, 77_98, 73_43, 11, 2_99, 3_33_10, 4, 1_58, 3_73_50, 9_40_77, 45_69, 2_99, 3_33_10, 90, 4, 5_28_40, 2_90, 4, 3_12_70, 1_12, 2_99, 6_82, 4, 5_28_40, 3_99_53, 1_40_79, 1_93, 5_25_19, 9_08_94, 1_78_94, 12_06_97, 11, 4_04_45, 5_51, 17, 10_19, 5_25_19, 9_08_94, 1_77_56, 9_63, 11, 4_04_45, 4_80, 17, 97_92, 11_20, 51_73, 13_93, 62_40, 1_67_86, 2_41, 12_09_96, 28, 12_45, 13_93, 11_82_40, 1_11_23, 10_19, 9_36_12, 26_91, 1_06_18, 9_80_58, 12_04_09, 19_28, 2_79, 4, 4_06_83, 3_67, 1_78, 2_07, 10_19, 1_03, 10_31_21, 5_06, 6_52_96, 5, 2], [12_80_22, 2_12_17, 3_67, 1_17, 12_54_50, 1_28, 7_19, 7, 73_08, 40, 9_36_12, 1_26_69, 11_16, 1_67_04, 71, 1_77_85, 36_99, 1_55_92, 35, 1_44, 95_84, 2_41, 1_19_43, 7_13, 9_50, 7_99, 22_47, 8_84_27, 1_50, 1_49, 11_88_13, 12_07_06, 10_19, 10_69_06, 8_15_18, 28, 12_24, 2_27_99, 3_97, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [12_80_22, 16_58, 12_33_11, 51_55, 55_78, 47_22, 2_79, 1_49_47, 23_66, 11_20, 11_97, 14, 13_48, 92_32, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowercase , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): """simple docstring""" __UpperCamelCase : List[str] = 'facebook/m2m100_418M' __UpperCamelCase : Any = [ 'In my opinion, there are two levels of response from the French government.', 'NSA Affair Emphasizes Complete Lack of Debate on Intelligence', ] __UpperCamelCase : Tuple = [ 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', ] # fmt: off __UpperCamelCase : Any = [EN_CODE, 593, 1_949, 115_781, 4, 71_586, 4_234, 60_633, 126_233, 432, 123_808, 15_592, 1_197, 117_132, 120_618, 5, 2] @classmethod def _snake_case (cls ): __lowerCAmelCase = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) __lowerCAmelCase = 1 return cls def _snake_case (self ): self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 12_80_06 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 12_80_22 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 12_80_76 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 12_80_63 ) def _snake_case (self ): __lowerCAmelCase = self.tokenizer.get_vocab() self.assertEqual(len(__lowercase ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , __lowercase ) def _snake_case (self ): __lowerCAmelCase = '''en''' __lowerCAmelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowercase ) def _snake_case (self ): self.assertIn(__lowercase , self.tokenizer.all_special_ids ) # fmt: off __lowerCAmelCase = [FR_CODE, 53_64, 82, 86_42, 4, 2_94, 47, 8, 1_40_28, 1_36, 32_86, 97_06, 6, 9_07_97, 6, 14_40_12, 1_62, 8_81_28, 3_00_61, 5, 2] # fmt: on __lowerCAmelCase = self.tokenizer.decode(__lowercase , skip_special_tokens=__lowercase ) __lowerCAmelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowercase ) self.assertEqual(__lowercase , __lowercase ) self.assertNotIn(self.tokenizer.eos_token , __lowercase ) def _snake_case (self ): __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(__lowercase ) __lowerCAmelCase = MaMaaaTokenizer.from_pretrained(__lowercase ) self.assertDictEqual(new_tok.lang_token_to_id , __lowercase ) @require_torch def _snake_case (self ): __lowerCAmelCase = '''en''' __lowerCAmelCase = '''fr''' __lowerCAmelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowercase , return_tensors='''pt''' ) __lowerCAmelCase = shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: __lowerCAmelCase = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def _snake_case (self ): __lowerCAmelCase = '''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) __lowerCAmelCase = '''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def _snake_case (self ): __lowerCAmelCase = '''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) __lowerCAmelCase = '''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def _snake_case (self ): __lowerCAmelCase = self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(__lowercase ) , { # en_XX, A, test, EOS '''input_ids''': [[12_80_22, 58, 41_83, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 12_80_06, } , )
9
'''simple docstring''' import argparse import datetime def __magic_name__( lowerCamelCase): __lowerCAmelCase = { '''0''': '''Sunday''', '''1''': '''Monday''', '''2''': '''Tuesday''', '''3''': '''Wednesday''', '''4''': '''Thursday''', '''5''': '''Friday''', '''6''': '''Saturday''', } __lowerCAmelCase = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(lowerCamelCase) < 1_1: raise ValueError('''Must be 10 characters long''') # Get month __lowerCAmelCase = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 1_3: raise ValueError('''Month must be between 1 - 12''') __lowerCAmelCase = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('''Date separator must be \'-\' or \'/\'''') # Get day __lowerCAmelCase = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 3_2: raise ValueError('''Date must be between 1 - 31''') # Get second separator __lowerCAmelCase = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('''Date separator must be \'-\' or \'/\'''') # Get year __lowerCAmelCase = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 4_5 < y < 8_5_0_0: raise ValueError( '''Year out of range. There has to be some sort of limit...right?''') # Get datetime obj for validation __lowerCAmelCase = datetime.date(int(lowerCamelCase), int(lowerCamelCase), int(lowerCamelCase)) # Start math if m <= 2: __lowerCAmelCase = y - 1 __lowerCAmelCase = m + 1_2 # maths var __lowerCAmelCase = int(str(lowerCamelCase)[:2]) __lowerCAmelCase = int(str(lowerCamelCase)[2:]) __lowerCAmelCase = int(2.6 * m - 5.39) __lowerCAmelCase = int(c / 4) __lowerCAmelCase = int(k / 4) __lowerCAmelCase = int(d + k) __lowerCAmelCase = int(t + u + v + x) __lowerCAmelCase = int(z - (2 * c)) __lowerCAmelCase = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('''The date was evaluated incorrectly. Contact developer.''') # Response __lowerCAmelCase = F"""Your date {date_input}, is a {days[str(lowerCamelCase)]}!""" return response if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase : List[str] = argparse.ArgumentParser( description=( """Find out what day of the week nearly any date is or was. Enter """ """date as a string in the mm-dd-yyyy or mm/dd/yyyy format""" ) ) parser.add_argument( """date_input""", type=str, help="""Date as a string (mm-dd-yyyy or mm/dd/yyyy)""" ) _UpperCAmelCase : Dict = parser.parse_args() zeller(args.date_input)
9
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : int = logging.get_logger(__name__) snake_case_ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowercase__ ( lowercase ): lowercase__ = """mobilenet_v1""" def __init__( self : List[Any] ,lowerCamelCase__ : List[str]=3 ,lowerCamelCase__ : Tuple=224 ,lowerCamelCase__ : str=1.0 ,lowerCamelCase__ : List[str]=8 ,lowerCamelCase__ : int="relu6" ,lowerCamelCase__ : str=True ,lowerCamelCase__ : Optional[Any]=0.9_9_9 ,lowerCamelCase__ : str=0.0_2 ,lowerCamelCase__ : Optional[Any]=0.0_0_1 ,**lowerCamelCase__ : Dict ,): '''simple docstring''' super().__init__(**lowerCamelCase__ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) _UpperCamelCase : Tuple = num_channels _UpperCamelCase : Tuple = image_size _UpperCamelCase : int = depth_multiplier _UpperCamelCase : Any = min_depth _UpperCamelCase : Optional[int] = hidden_act _UpperCamelCase : List[Any] = tf_padding _UpperCamelCase : Optional[int] = classifier_dropout_prob _UpperCamelCase : List[Any] = initializer_range _UpperCamelCase : List[str] = layer_norm_eps class lowercase__ ( lowercase ): lowercase__ = version.parse("""1.11""" ) @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' return 1E-4
83
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class lowercase__ ( lowercase ): @require_torch def UpperCamelCase_ ( self : Dict ): '''simple docstring''' # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCamelCase : Any = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _UpperCamelCase : Dict = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _UpperCamelCase : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _UpperCamelCase : Optional[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(lowerCamelCase__ ) BertModel.from_pretrained(lowerCamelCase__ ) BertTokenizer.from_pretrained(lowerCamelCase__ ) pipeline(task='fill-mask' ,model=lowerCamelCase__ ) # baseline - just load from_pretrained with normal network _UpperCamelCase : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _UpperCamelCase : Dict = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCamelCase : str = '1' _UpperCamelCase : Union[str, Any] = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCamelCase : Any = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _UpperCamelCase : Any = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _UpperCamelCase : Any = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _UpperCamelCase : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(lowerCamelCase__ ) BertModel.from_pretrained(lowerCamelCase__ ) BertTokenizer.from_pretrained(lowerCamelCase__ ) pipeline(task='fill-mask' ,model=lowerCamelCase__ ) # baseline - just load from_pretrained with normal network _UpperCamelCase : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _UpperCamelCase : List[Any] = self.get_env() _UpperCamelCase : Dict = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _UpperCamelCase : Optional[Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _UpperCamelCase : str = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _UpperCamelCase : Any = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _UpperCamelCase : Optional[int] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _UpperCamelCase : Optional[Any] = self.get_env() _UpperCamelCase : int = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _UpperCamelCase : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCamelCase : Dict = '1' _UpperCamelCase : Dict = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : str ): '''simple docstring''' _UpperCamelCase : int = '\nfrom transformers import pipeline\n ' _UpperCamelCase : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _UpperCamelCase : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _UpperCamelCase : Union[str, Any] = self.get_env() _UpperCamelCase : List[Any] = '1' _UpperCamelCase : Tuple = [sys.executable, '-c', '\n'.join([load, mock, run] )] _UpperCamelCase : int = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Optional[int] = '\nfrom transformers import AutoModel\n ' _UpperCamelCase : int = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _UpperCamelCase : Any = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _UpperCamelCase : Optional[Any] = self.get_env() _UpperCamelCase : Optional[int] = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _UpperCamelCase : List[Any] = '1' _UpperCamelCase : Dict = subprocess.run(lowerCamelCase__ ,env=lowerCamelCase__ ,check=lowerCamelCase__ ,capture_output=lowerCamelCase__ ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
83
1
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=3 , lowercase=32 , lowercase=3 , lowercase=10 , lowercase=[10, 20, 30, 40] , lowercase=[1, 1, 2, 1] , lowercase=True , lowercase=True , lowercase="relu" , lowercase=3 , lowercase=None , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = parent a__ : Any = batch_size a__ : Dict = image_size a__ : List[str] = num_channels a__ : Dict = embeddings_size a__ : List[Any] = hidden_sizes a__ : int = depths a__ : str = is_training a__ : int = use_labels a__ : List[Any] = hidden_act a__ : Optional[int] = num_labels a__ : Dict = scope a__ : List[str] = len(_snake_case) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a__ : List[Any] = None if self.use_labels: a__ : int = ids_tensor([self.batch_size] , self.num_labels) a__ : int = self.get_config() return config, pixel_values, labels def __lowercase ( self) -> Tuple: '''simple docstring''' return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __lowercase ( self , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : Any = TFResNetModel(config=_snake_case) a__ : Tuple = model(_snake_case) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase ( self , lowercase , lowercase , lowercase) -> List[Any]: '''simple docstring''' a__ : Optional[Any] = self.num_labels a__ : int = TFResNetForImageClassification(_snake_case) a__ : Dict = model(_snake_case , labels=_snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] = self.prepare_config_and_inputs() a__ , a__ , a__ : Dict = config_and_inputs a__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () __A : str = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) __A : List[str] = False __A : Tuple = False __A : Any = False __A : Dict = False __A : Optional[Any] = False def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : Optional[int] = TFResNetModelTester(self) a__ : str = ConfigTester(self , config_class=_snake_case , has_text_modality=_snake_case) def __lowercase ( 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 __lowercase ( self) -> str: '''simple docstring''' return @unittest.skip(reason='ResNet does not use inputs_embeds') def __lowercase ( self) -> Any: '''simple docstring''' pass @unittest.skip(reason='ResNet does not support input and output embeddings') def __lowercase ( self) -> int: '''simple docstring''' pass def __lowercase ( self) -> str: '''simple docstring''' a__ , a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : List[str] = model_class(_snake_case) a__ : List[str] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[int] = [*signature.parameters.keys()] a__ : List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _snake_case) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case) def __lowercase ( self) -> str: '''simple docstring''' def check_hidden_states_output(lowercase , lowercase , lowercase): a__ : str = model_class(_snake_case) a__ : Optional[Any] = model(**self._prepare_for_class(_snake_case , _snake_case)) a__ : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a__ : Dict = self.model_tester.num_stages self.assertEqual(len(_snake_case) , expected_num_stages + 1) # ResNet'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] , ) a__ , a__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[int] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: a__ : str = layer_type a__ : List[str] = True check_hidden_states_output(_snake_case , _snake_case , _snake_case) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : Tuple = True check_hidden_states_output(_snake_case , _snake_case , _snake_case) def __lowercase ( self) -> Dict: '''simple docstring''' a__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case) @slow def __lowercase ( self) -> int: '''simple docstring''' for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = TFResNetModel.from_pretrained(_snake_case) self.assertIsNotNone(_snake_case) def A_ ( ) -> Union[str, Any]: a__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self) -> Optional[Any]: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Tuple = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) a__ : List[str] = self.default_image_processor a__ : Optional[int] = prepare_img() a__ : str = image_processor(images=_snake_case , return_tensors='tf') # forward pass a__ : List[str] = model(**_snake_case) # verify the logits a__ : int = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , _snake_case) a__ : Optional[int] = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _snake_case , atol=1e-4))
361
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase : List[str] = { """configuration_clip""": [ """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPConfig""", """CLIPOnnxConfig""", """CLIPTextConfig""", """CLIPVisionConfig""", ], """processing_clip""": ["""CLIPProcessor"""], """tokenization_clip""": ["""CLIPTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Tuple = ["""CLIPTokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[int] = ["""CLIPFeatureExtractor"""] lowercase : Union[str, Any] = ["""CLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = [ """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPModel""", """CLIPPreTrainedModel""", """CLIPTextModel""", """CLIPTextModelWithProjection""", """CLIPVisionModel""", """CLIPVisionModelWithProjection""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[str] = [ """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCLIPModel""", """TFCLIPPreTrainedModel""", """TFCLIPTextModel""", """TFCLIPVisionModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Any = [ """FlaxCLIPModel""", """FlaxCLIPPreTrainedModel""", """FlaxCLIPTextModel""", """FlaxCLIPTextPreTrainedModel""", """FlaxCLIPVisionModel""", """FlaxCLIPVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
225
0
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def _UpperCAmelCase ( snake_case , snake_case , snake_case=None ): """simple docstring""" assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match' _lowerCAmelCase = nn.Parameter(snake_case ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match' _lowerCAmelCase = nn.Parameter(snake_case ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = np.asarray(weights[0] ) _lowerCAmelCase = np.asarray(weights[1] ) _lowerCAmelCase = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case ).view(-1 , snake_case ).contiguous().transpose(0 , 1 ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = np.asarray(weights[0] ) _lowerCAmelCase = np.asarray(weights[1] ) _lowerCAmelCase = np.asarray(weights[2] ) _lowerCAmelCase = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.key , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case ).transpose(1 , 2 ).contiguous().view(-1 , snake_case ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case ).view(-1 , snake_case ).contiguous().transpose(0 , 1 ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = weights[0][0][0] _lowerCAmelCase = np.asarray(layer_norm_a[0] ) _lowerCAmelCase = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # lsh weights + output _lowerCAmelCase = weights[0][1] if len(snake_case ) < 4: set_layer_weights_in_torch_lsh(snake_case , torch_block.attention , snake_case ) else: set_layer_weights_in_torch_local(snake_case , torch_block.attention , snake_case ) # intermediate weighs _lowerCAmelCase = weights[2][0][1][2] # Chunked Feed Forward if len(snake_case ) == 4: _lowerCAmelCase = intermediate_weights[2] # layernorm 2 _lowerCAmelCase = np.asarray(intermediate_weights[0][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # intermediate dense _lowerCAmelCase = np.asarray(intermediate_weights[1][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) # intermediate out _lowerCAmelCase = np.asarray(intermediate_weights[4][0] ) _lowerCAmelCase = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = torch_model.reformer # word embeds _lowerCAmelCase = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(snake_case ) , ) if isinstance(weights[3] , snake_case ): _lowerCAmelCase = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _lowerCAmelCase = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'{position_embeddings[emb_idx]} emb does not match' _lowerCAmelCase = nn.Parameter(torch.tensor(snake_case ) ) _lowerCAmelCase = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( snake_case ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _lowerCAmelCase = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(snake_case , snake_case , snake_case ) # output layer norm _lowerCAmelCase = np.asarray(weights[7][0] ) _lowerCAmelCase = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(snake_case ) , torch.tensor(snake_case ) , ) # output embeddings _lowerCAmelCase = np.asarray(weights[9][0] ) _lowerCAmelCase = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(snake_case ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case ) , ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = ReformerConfig.from_json_file(snake_case ) print(F'Building PyTorch model from configuration: {config}' ) _lowerCAmelCase = ReformerModelWithLMHead(snake_case ) with open(snake_case , """rb""" ) as f: _lowerCAmelCase = pickle.load(snake_case )["""weights"""] set_model_weights_in_torch(snake_case , snake_case , config.hidden_size ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , snake_case ) if __name__ == "__main__": A__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) A__ = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
82
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> List[str]: '''simple docstring''' with open(__A ) as metadata_file: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = LukeConfig(use_entity_aware_attention=__A , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase__ = torch.load(__A , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase__ = load_original_entity_vocab(__A ) # add an entry for [MASK2] UpperCamelCase__ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase__ = AddedToken("<ent>" , lstrip=__A , rstrip=__A ) UpperCamelCase__ = AddedToken("<ent2>" , lstrip=__A , rstrip=__A ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__A ) with open(os.path.join(__A , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase__ = json.load(__A ) UpperCamelCase__ = "MLukeTokenizer" with open(os.path.join(__A , "tokenizer_config.json" ) , "w" ) as f: json.dump(__A , __A ) with open(os.path.join(__A , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__A , __A ) UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) # Initialize the embeddings of the special tokens UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase__ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase__ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase__ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase__ = state_dict[bias_name] UpperCamelCase__ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase__ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase__ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase__ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] UpperCamelCase__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase__ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase__ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase__ = state_dict["entity_predictions.bias"] UpperCamelCase__ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase__ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase__ = LukeForMaskedLM(config=__A ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase__ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase__ = state_dict[key] else: UpperCamelCase__ = state_dict[key] UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__A , strict=__A ) if set(__A ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(__A ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A , task="entity_classification" ) UpperCamelCase__ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase__ = (0, 9) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 33, 768) ) UpperCamelCase__ = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase__ = torch.Size((1, 1, 768) ) UpperCamelCase__ = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __A , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase__ = MLukeTokenizer.from_pretrained(__A ) UpperCamelCase__ = "Tokyo is the capital of <mask>." UpperCamelCase__ = (24, 30) UpperCamelCase__ = tokenizer(__A , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase__ = model(**__A ) UpperCamelCase__ = encoding["input_ids"][0].tolist() UpperCamelCase__ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase__ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__A ) UpperCamelCase__ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase__ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__A ) ) model.save_pretrained(__A ) def _UpperCamelCase ( __A ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase__ = [json.loads(__A ) for line in open(__A )] UpperCamelCase__ = {} for entry in data: UpperCamelCase__ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase__ = entity_id break UpperCamelCase__ = F'''{language}:{entity_name}''' UpperCamelCase__ = entity_id return new_mapping if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) a__ : Any = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
80
0
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = ["""vqvae"""] def __init__( self : Optional[int] , lowerCAmelCase_ : AutoencoderKL , lowerCAmelCase_ : UNetaDConditionModel , lowerCAmelCase_ : Mel , lowerCAmelCase_ : Union[DDIMScheduler, DDPMScheduler] , ) -> Any: super().__init__() self.register_modules(unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , mel=lowerCAmelCase_ , vqvae=lowerCAmelCase_ ) def lowercase ( self : Optional[Any] ) -> int: return 5_0 if isinstance(self.scheduler , lowerCAmelCase_ ) else 1_0_0_0 @torch.no_grad() def __call__( self : List[Any] , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : str = None , lowerCAmelCase_ : np.ndarray = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : int = None , lowerCAmelCase_ : torch.Generator = None , lowerCAmelCase_ : float = 0 , lowerCAmelCase_ : float = 0 , lowerCAmelCase_ : torch.Generator = None , lowerCAmelCase_ : float = 0 , lowerCAmelCase_ : torch.Tensor = None , lowerCAmelCase_ : torch.Tensor = None , lowerCAmelCase_ : int=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: __lowerCAmelCase = steps or self.get_default_steps() self.scheduler.set_timesteps(lowerCAmelCase_ ) __lowerCAmelCase = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: __lowerCAmelCase = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: __lowerCAmelCase = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowerCAmelCase_ , device=self.device , ) __lowerCAmelCase = noise __lowerCAmelCase = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowerCAmelCase_ , lowerCAmelCase_ ) __lowerCAmelCase = self.mel.audio_slice_to_image(lowerCAmelCase_ ) __lowerCAmelCase = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) __lowerCAmelCase = (input_image / 2_5_5) * 2 - 1 __lowerCAmelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: __lowerCAmelCase = self.vqvae.encode(torch.unsqueeze(lowerCAmelCase_ , 0 ) ).latent_dist.sample( generator=lowerCAmelCase_ )[0] __lowerCAmelCase = self.vqvae.config.scaling_factor * input_images if start_step > 0: __lowerCAmelCase = self.scheduler.add_noise(lowerCAmelCase_ , lowerCAmelCase_ , self.scheduler.timesteps[start_step - 1] ) __lowerCAmelCase = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) __lowerCAmelCase = int(mask_start_secs * pixels_per_second ) __lowerCAmelCase = int(mask_end_secs * pixels_per_second ) __lowerCAmelCase = self.scheduler.add_noise(lowerCAmelCase_ , lowerCAmelCase_ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowerCAmelCase_ ): __lowerCAmelCase = self.unet(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )['sample'] else: __lowerCAmelCase = self.unet(lowerCAmelCase_ , lowerCAmelCase_ )['sample'] if isinstance(self.scheduler , lowerCAmelCase_ ): __lowerCAmelCase = self.scheduler.step( model_output=lowerCAmelCase_ , timestep=lowerCAmelCase_ , sample=lowerCAmelCase_ , eta=lowerCAmelCase_ , generator=lowerCAmelCase_ , )['prev_sample'] else: __lowerCAmelCase = self.scheduler.step( model_output=lowerCAmelCase_ , timestep=lowerCAmelCase_ , sample=lowerCAmelCase_ , generator=lowerCAmelCase_ , )['prev_sample'] if mask is not None: if mask_start > 0: __lowerCAmelCase = mask[:, step, :, :mask_start] if mask_end > 0: __lowerCAmelCase = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance __lowerCAmelCase = 1 / self.vqvae.config.scaling_factor * images __lowerCAmelCase = self.vqvae.decode(lowerCAmelCase_ )['sample'] __lowerCAmelCase = (images / 2 + 0.5).clamp(0 , 1 ) __lowerCAmelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() __lowerCAmelCase = (images * 2_5_5).round().astype('uint8' ) __lowerCAmelCase = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowerCAmelCase_ , mode='RGB' ).convert('L' ) for _ in images) ) __lowerCAmelCase = [self.mel.image_to_audio(lowerCAmelCase_ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowerCAmelCase_ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowerCAmelCase_ ) ) @torch.no_grad() def lowercase ( self : int , lowerCAmelCase_ : List[Image.Image] , lowerCAmelCase_ : int = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , lowerCAmelCase_ ) self.scheduler.set_timesteps(lowerCAmelCase_ ) __lowerCAmelCase = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) __lowerCAmelCase = (sample / 2_5_5) * 2 - 1 __lowerCAmelCase = torch.Tensor(lowerCAmelCase_ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): __lowerCAmelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps __lowerCAmelCase = self.scheduler.alphas_cumprod[t] __lowerCAmelCase = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) __lowerCAmelCase = 1 - alpha_prod_t __lowerCAmelCase = self.unet(lowerCAmelCase_ , lowerCAmelCase_ )['sample'] __lowerCAmelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output __lowerCAmelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) __lowerCAmelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def lowercase ( lowerCAmelCase_ : torch.Tensor , lowerCAmelCase_ : torch.Tensor , lowerCAmelCase_ : float ) -> torch.Tensor: __lowerCAmelCase = acos(torch.dot(torch.flatten(lowerCAmelCase_ ) , torch.flatten(lowerCAmelCase_ ) ) / torch.norm(lowerCAmelCase_ ) / torch.norm(lowerCAmelCase_ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowerCAmelCase_ ) + sin(alpha * theta ) * xa / sin(lowerCAmelCase_ )
207
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def a_ ( lowerCAmelCase_ : Optional[Any] ): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp >= 0X3400 and cp <= 0X4dbf) # or (cp >= 0X20000 and cp <= 0X2a6df) # or (cp >= 0X2a700 and cp <= 0X2b73f) # or (cp >= 0X2b740 and cp <= 0X2b81f) # or (cp >= 0X2b820 and cp <= 0X2ceaf) # or (cp >= 0Xf900 and cp <= 0Xfaff) or (cp >= 0X2f800 and cp <= 0X2fa1f) # ): # return True return False def a_ ( lowerCAmelCase_ : str ): # word like '180' or '身高' or '神' for char in word: __lowerCAmelCase = ord(lowerCAmelCase_ ) if not _is_chinese_char(lowerCAmelCase_ ): return 0 return 1 def a_ ( lowerCAmelCase_ : List[str] ): __lowerCAmelCase = set() for token in tokens: __lowerCAmelCase = len(lowerCAmelCase_ ) > 1 and is_chinese(lowerCAmelCase_ ) if chinese_word: word_set.add(lowerCAmelCase_ ) __lowerCAmelCase = list(lowerCAmelCase_ ) return word_list def a_ ( lowerCAmelCase_ : List[str], lowerCAmelCase_ : set() ): if not chinese_word_set: return bert_tokens __lowerCAmelCase = max([len(lowerCAmelCase_ ) for w in chinese_word_set] ) __lowerCAmelCase = bert_tokens __lowerCAmelCase , __lowerCAmelCase = 0, len(lowerCAmelCase_ ) while start < end: __lowerCAmelCase = True if is_chinese(bert_word[start] ): __lowerCAmelCase = min(end - start, lowerCAmelCase_ ) for i in range(lowerCAmelCase_, 1, -1 ): __lowerCAmelCase = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1, start + i ): __lowerCAmelCase = '##' + bert_word[j] __lowerCAmelCase = start + i __lowerCAmelCase = False break if single_word: start += 1 return bert_word def a_ ( lowerCAmelCase_ : List[str], lowerCAmelCase_ : LTP, lowerCAmelCase_ : BertTokenizer ): __lowerCAmelCase = [] for i in range(0, len(lowerCAmelCase_ ), 100 ): __lowerCAmelCase = ltp_tokenizer.pipeline(lines[i : i + 100], tasks=['cws'] ).cws __lowerCAmelCase = [get_chinese_word(lowerCAmelCase_ ) for r in res] ltp_res.extend(lowerCAmelCase_ ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) __lowerCAmelCase = [] for i in range(0, len(lowerCAmelCase_ ), 100 ): __lowerCAmelCase = bert_tokenizer(lines[i : i + 100], add_special_tokens=lowerCAmelCase_, truncation=lowerCAmelCase_, max_length=512 ) bert_res.extend(res['input_ids'] ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) __lowerCAmelCase = [] for input_ids, chinese_word in zip(lowerCAmelCase_, lowerCAmelCase_ ): __lowerCAmelCase = [] for id in input_ids: __lowerCAmelCase = bert_tokenizer._convert_id_to_token(lowerCAmelCase_ ) input_tokens.append(lowerCAmelCase_ ) __lowerCAmelCase = add_sub_symbol(lowerCAmelCase_, lowerCAmelCase_ ) __lowerCAmelCase = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase_ ): if token[:2] == "##": __lowerCAmelCase = token[2:] # save chinese tokens' pos if len(lowerCAmelCase_ ) == 1 and _is_chinese_char(ord(lowerCAmelCase_ ) ): ref_id.append(lowerCAmelCase_ ) ref_ids.append(lowerCAmelCase_ ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) return ref_ids def a_ ( lowerCAmelCase_ : int ): # For Chinese (Ro)Bert, the best result is from : RoBERTa-wwm-ext (https://github.com/ymcui/Chinese-BERT-wwm) # If we want to fine-tune these model, we have to use same tokenizer : LTP (https://github.com/HIT-SCIR/ltp) with open(args.file_name, 'r', encoding='utf-8' ) as f: __lowerCAmelCase = f.readlines() __lowerCAmelCase = [line.strip() for line in data if len(lowerCAmelCase_ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' __lowerCAmelCase = LTP(args.ltp ) # faster in GPU device __lowerCAmelCase = BertTokenizer.from_pretrained(args.bert ) __lowerCAmelCase = prepare_ref(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) with open(args.save_path, 'w', encoding='utf-8' ) as f: __lowerCAmelCase = [json.dumps(lowerCAmelCase_ ) + '\n' for ref in ref_ids] f.writelines(lowerCAmelCase_ ) if __name__ == "__main__": _snake_case : int = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', required=False, type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', required=False, type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path', ) parser.add_argument( '--bert', required=False, type=str, default='./resources/robert', help='resources for Bert tokenizer', ) parser.add_argument( '--save_path', required=False, type=str, default='./resources/ref.txt', help='path to save res', ) _snake_case : List[str] = parser.parse_args() main(args)
207
1
"""simple docstring""" from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" if not is_accelerate_available(): return method _snake_case : Union[str, Any] = version.parse(accelerate.__version__ ).base_version if version.parse(snake_case__ ) < version.parse("""0.17.0""" ): return method def wrapper(self : Union[str, Any] , *snake_case__ : List[Any] , **snake_case__ : str ): if hasattr(self , """_hf_hook""" ) and hasattr(self._hf_hook , """pre_forward""" ): self._hf_hook.pre_forward(self ) return method(self , *snake_case__ , **snake_case__ ) return wrapper
64
'''simple docstring''' import os import numpy import onnx def a__ ( lowercase : List[str], lowercase : str ) -> List[Any]: """simple docstring""" _UpperCamelCase = a.name _UpperCamelCase = b.name _UpperCamelCase = '''''' _UpperCamelCase = '''''' _UpperCamelCase = a == b _UpperCamelCase = name_a _UpperCamelCase = name_b return res def a__ ( lowercase : List[str], lowercase : List[Any], lowercase : Tuple ) -> int: """simple docstring""" for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(lowercase, lowercase ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g, lowercase, lowercase ) _graph_replace_input_with(node_proto.attribute[1].g, lowercase, lowercase ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g, lowercase, lowercase ) def a__ ( lowercase : Any, lowercase : Union[str, Any], lowercase : Dict ) -> Tuple: """simple docstring""" for n in graph_proto.node: _node_replace_input_with(lowercase, lowercase, lowercase ) def a__ ( lowercase : Optional[int], lowercase : Union[str, Any], lowercase : Optional[int] ) -> Tuple: """simple docstring""" _UpperCamelCase = list(model.graph.initializer ) _UpperCamelCase = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i _UpperCamelCase = inits[i].name _UpperCamelCase = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph, lowercase, lowercase ) def a__ ( lowercase : Dict ) -> Dict: """simple docstring""" _UpperCamelCase = os.path.dirname(lowercase ) _UpperCamelCase = os.path.basename(lowercase ) _UpperCamelCase = onnx.load(os.path.join(lowercase, lowercase ) ) _UpperCamelCase = list(model.graph.initializer ) _UpperCamelCase = set() _UpperCamelCase = {} _UpperCamelCase = [] _UpperCamelCase = 0 for i in range(len(lowercase ) ): if i in dup_set: continue for j in range(i + 1, len(lowercase ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i], inits[j] ): dup_set.add(lowercase ) dup_set.add(lowercase ) _UpperCamelCase = inits[j].data_type _UpperCamelCase = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print('''unexpected data type: ''', lowercase ) total_reduced_size += mem_size _UpperCamelCase = inits[i].name _UpperCamelCase = inits[j].name if name_i in dup_map: dup_map[name_i].append(lowercase ) else: _UpperCamelCase = [name_j] ind_to_replace.append((j, i) ) print('''total reduced size: ''', total_reduced_size / 1024 / 1024 / 1024, '''GB''' ) _UpperCamelCase = sorted(lowercase ) _remove_dup_initializers_from_model(lowercase, lowercase, lowercase ) _UpperCamelCase = '''optimized_''' + model_file_name _UpperCamelCase = os.path.join(lowercase, lowercase ) onnx.save(lowercase, lowercase ) return new_model
324
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """sayakpaul/vit-msn-base""": """https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json""", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _snake_case ( lowercase__): UpperCamelCase__ : Union[str, Any] ="""vit_msn""" def __init__( self : Tuple, __lowercase : Union[str, Any]=768, __lowercase : Dict=12, __lowercase : Dict=12, __lowercase : Dict=3072, __lowercase : int="gelu", __lowercase : Union[str, Any]=0.0, __lowercase : Optional[Any]=0.0, __lowercase : Tuple=0.02, __lowercase : Optional[Any]=1e-0_6, __lowercase : int=224, __lowercase : List[Any]=16, __lowercase : str=3, __lowercase : int=True, **__lowercase : Dict, ): super().__init__(**__lowercase ) lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = qkv_bias
224
from pathlib import Path import fire def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = Path(SCREAMING_SNAKE_CASE_ ) lowercase__ = Path(SCREAMING_SNAKE_CASE_ ) dest_dir.mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) for path in src_dir.iterdir(): lowercase__ = [x.rstrip() for x in list(path.open().readlines() )][:n] lowercase__ = dest_dir.joinpath(path.name ) print(SCREAMING_SNAKE_CASE_ ) dest_path.open("w" ).write("\n".join(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": fire.Fire(minify)
224
1
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A: Union[str, Any] = logging.get_logger(__name__) A: str = { "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 SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : Any = 'informer' __lowerCAmelCase : str = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "student_t" , _SCREAMING_SNAKE_CASE = "nll" , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "mean" , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 64 , _SCREAMING_SNAKE_CASE = 32 , _SCREAMING_SNAKE_CASE = 32 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = "gelu" , _SCREAMING_SNAKE_CASE = 0.05 , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 100 , _SCREAMING_SNAKE_CASE = 0.02 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE = "prob" , _SCREAMING_SNAKE_CASE = 5 , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: '''simple docstring''' UpperCAmelCase : Optional[Any] = prediction_length UpperCAmelCase : Any = context_length or prediction_length UpperCAmelCase : Tuple = distribution_output UpperCAmelCase : Optional[int] = loss UpperCAmelCase : int = input_size UpperCAmelCase : Union[str, Any] = num_time_features UpperCAmelCase : Dict = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] UpperCAmelCase : Optional[int] = scaling UpperCAmelCase : Tuple = num_dynamic_real_features UpperCAmelCase : List[Any] = num_static_real_features UpperCAmelCase : Any = 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`""" ) UpperCAmelCase : List[str] = cardinality else: UpperCAmelCase : List[str] = [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`""" ) UpperCAmelCase : int = embedding_dimension else: UpperCAmelCase : Optional[int] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] UpperCAmelCase : Optional[Any] = num_parallel_samples # Transformer architecture configuration UpperCAmelCase : int = input_size * len(self.lags_sequence ) + self._number_of_features UpperCAmelCase : Any = d_model UpperCAmelCase : List[Any] = encoder_attention_heads UpperCAmelCase : Optional[Any] = decoder_attention_heads UpperCAmelCase : int = encoder_ffn_dim UpperCAmelCase : Any = decoder_ffn_dim UpperCAmelCase : str = encoder_layers UpperCAmelCase : List[str] = decoder_layers UpperCAmelCase : List[Any] = dropout UpperCAmelCase : Tuple = attention_dropout UpperCAmelCase : Any = activation_dropout UpperCAmelCase : List[str] = encoder_layerdrop UpperCAmelCase : List[Any] = decoder_layerdrop UpperCAmelCase : str = activation_function UpperCAmelCase : List[str] = init_std UpperCAmelCase : Any = use_cache # Informer UpperCAmelCase : Any = attention_type UpperCAmelCase : Tuple = sampling_factor UpperCAmelCase : int = distil super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
109
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def _snake_case ( UpperCamelCase : int = 1000000 , UpperCamelCase : int = 10 ): UpperCAmelCase : defaultdict = defaultdict(UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCAmelCase : str = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCAmelCase : Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f"""{solution() = }""")
109
1
"""simple docstring""" import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class _lowerCAmelCase ( nn.Module ): __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : float = 0.0 __UpperCAmelCase : int = 1 __UpperCAmelCase : int = 1 __UpperCAmelCase : bool = True __UpperCAmelCase : bool = False __UpperCAmelCase : bool = False __UpperCAmelCase : bool = False __UpperCAmelCase : jnp.dtype = jnp.floataa def lowerCamelCase ( self ) -> List[str]: '''simple docstring''' snake_case : List[Any] = [] snake_case : List[str] = [] for i in range(self.num_layers ): snake_case : Optional[Any] = self.in_channels if i == 0 else self.out_channels snake_case : List[str] = FlaxResnetBlockaD( in_channels=UpperCamelCase__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(UpperCamelCase__ ) snake_case : Any = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(UpperCamelCase__ ) snake_case : Union[str, Any] = resnets snake_case : Dict = attentions if self.add_downsample: snake_case : Optional[Any] = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ) -> int: '''simple docstring''' snake_case : Optional[int] = () for resnet, attn in zip(self.resnets , self.attentions ): snake_case : Optional[int] = resnet(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) snake_case : List[Any] = attn(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) output_states += (hidden_states,) if self.add_downsample: snake_case : List[Any] = self.downsamplers_a(UpperCamelCase__ ) output_states += (hidden_states,) return hidden_states, output_states class _lowerCAmelCase ( nn.Module ): __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : float = 0.0 __UpperCAmelCase : int = 1 __UpperCAmelCase : bool = True __UpperCAmelCase : jnp.dtype = jnp.floataa def lowerCamelCase ( self ) -> int: '''simple docstring''' snake_case : str = [] for i in range(self.num_layers ): snake_case : Union[str, Any] = self.in_channels if i == 0 else self.out_channels snake_case : List[str] = FlaxResnetBlockaD( in_channels=UpperCamelCase__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(UpperCamelCase__ ) snake_case : Optional[Any] = resnets if self.add_downsample: snake_case : Dict = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ) -> Tuple: '''simple docstring''' snake_case : str = () for resnet in self.resnets: snake_case : Tuple = resnet(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) output_states += (hidden_states,) if self.add_downsample: snake_case : List[str] = self.downsamplers_a(UpperCamelCase__ ) output_states += (hidden_states,) return hidden_states, output_states class _lowerCAmelCase ( nn.Module ): __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : float = 0.0 __UpperCAmelCase : int = 1 __UpperCAmelCase : int = 1 __UpperCAmelCase : bool = True __UpperCAmelCase : bool = False __UpperCAmelCase : bool = False __UpperCAmelCase : bool = False __UpperCAmelCase : jnp.dtype = jnp.floataa def lowerCamelCase ( self ) -> Tuple: '''simple docstring''' snake_case : int = [] snake_case : int = [] for i in range(self.num_layers ): snake_case : str = self.in_channels if (i == self.num_layers - 1) else self.out_channels snake_case : Optional[Any] = self.prev_output_channel if i == 0 else self.out_channels snake_case : Tuple = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(UpperCamelCase__ ) snake_case : List[Any] = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(UpperCamelCase__ ) snake_case : Dict = resnets snake_case : Any = attentions if self.add_upsample: snake_case : List[Any] = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ) -> Optional[Any]: '''simple docstring''' for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states snake_case : List[Any] = res_hidden_states_tuple[-1] snake_case : Any = res_hidden_states_tuple[:-1] snake_case : Optional[Any] = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) snake_case : Optional[int] = resnet(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) snake_case : int = attn(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) if self.add_upsample: snake_case : Any = self.upsamplers_a(UpperCamelCase__ ) return hidden_states class _lowerCAmelCase ( nn.Module ): __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : int __UpperCAmelCase : float = 0.0 __UpperCAmelCase : int = 1 __UpperCAmelCase : bool = True __UpperCAmelCase : jnp.dtype = jnp.floataa def lowerCamelCase ( self ) -> str: '''simple docstring''' snake_case : Optional[int] = [] for i in range(self.num_layers ): snake_case : Tuple = self.in_channels if (i == self.num_layers - 1) else self.out_channels snake_case : Dict = self.prev_output_channel if i == 0 else self.out_channels snake_case : Tuple = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(UpperCamelCase__ ) snake_case : Any = resnets if self.add_upsample: snake_case : Any = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ) -> List[Any]: '''simple docstring''' for resnet in self.resnets: # pop res hidden states snake_case : Dict = res_hidden_states_tuple[-1] snake_case : Tuple = res_hidden_states_tuple[:-1] snake_case : Any = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) snake_case : Optional[Any] = resnet(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) if self.add_upsample: snake_case : List[str] = self.upsamplers_a(UpperCamelCase__ ) return hidden_states class _lowerCAmelCase ( nn.Module ): __UpperCAmelCase : int __UpperCAmelCase : float = 0.0 __UpperCAmelCase : int = 1 __UpperCAmelCase : int = 1 __UpperCAmelCase : bool = False __UpperCAmelCase : bool = False __UpperCAmelCase : jnp.dtype = jnp.floataa def lowerCamelCase ( self ) -> Optional[int]: '''simple docstring''' snake_case : List[Any] = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] snake_case : Dict = [] for _ in range(self.num_layers ): snake_case : Union[str, Any] = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(UpperCamelCase__ ) snake_case : Any = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(UpperCamelCase__ ) snake_case : Any = resnets snake_case : Any = attentions def __call__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ) -> Optional[int]: '''simple docstring''' snake_case : List[str] = self.resnets[0](UpperCamelCase__ , UpperCamelCase__ ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): snake_case : List[Any] = attn(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) snake_case : Tuple = resnet(UpperCamelCase__ , UpperCamelCase__ , deterministic=UpperCamelCase__ ) return hidden_states
112
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __snake_case = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class _lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = True , ) -> Tuple: '''simple docstring''' snake_case : List[Any] = [file for file in os.listdir(UpperCamelCase__ ) if os.path.isfile(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) )] if identifier is not None: snake_case : Optional[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): for n_ in n_identifier: snake_case : str = [file for file in files if n_ not in file] else: snake_case : str = [file for file in files if n_identifier not in file] snake_case : Tuple = ignore_files or [] ignore_files.append("__init__.py" ) snake_case : Optional[Any] = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , UpperCamelCase__ ) if only_modules: snake_case : str = file.split("." )[0] try: snake_case : Optional[int] = getattr(UpperCamelCase__ , UpperCamelCase__ ) snake_case : str = doctest.DocTestSuite(UpperCamelCase__ ) snake_case : Optional[Any] = unittest.TextTestRunner().run(UpperCamelCase__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: snake_case : Tuple = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def lowerCamelCase ( self ) -> str: '''simple docstring''' snake_case : Tuple = Path("src/transformers" ) snake_case : List[Any] = "modeling" snake_case : Dict = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ , ignore_files=UpperCamelCase__ ) def lowerCamelCase ( self ) -> Dict: '''simple docstring''' snake_case : Optional[Any] = Path("src/transformers" ) snake_case : Optional[Any] = "tokenization" self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> List[str]: '''simple docstring''' snake_case : Union[str, Any] = Path("src/transformers" ) snake_case : Optional[Any] = "configuration" self.analyze_directory(UpperCamelCase__ , identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> Optional[Any]: '''simple docstring''' snake_case : List[str] = Path("src/transformers" ) snake_case : List[str] = ["configuration", "modeling", "tokenization"] self.analyze_directory(UpperCamelCase__ , n_identifier=UpperCamelCase__ ) def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' snake_case : Any = Path("docs/source" ) snake_case : Tuple = ["favicon.ico"] self.analyze_directory(UpperCamelCase__ , ignore_files=UpperCamelCase__ , only_modules=UpperCamelCase__ )
112
1
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCAmelCase__ = float('nan') class lowerCAmelCase__ : '''simple docstring''' def __init__( self , __lowerCamelCase) -> Optional[Any]: _A : List[Any] = sys.stdout _A : str = open(__lowerCamelCase , "a") def __getattr__( self , __lowerCamelCase) -> List[str]: return getattr(self.stdout , __lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase) -> str: self.stdout.write(__lowerCamelCase) # strip tqdm codes self.file.write(re.sub(r"^.*\r" , "" , __lowerCamelCase , 0 , re.M)) def _UpperCAmelCase (UpperCamelCase__ : str=80 , UpperCamelCase__ : Tuple=False ): _A : Tuple = [] # deal with critical env vars _A : Dict = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: _A : Optional[int] = os.environ.get(UpperCamelCase__ , UpperCamelCase__ ) if val is not None: cmd.append(f"{key}={val}" ) # python executable (not always needed if the script is executable) _A : Optional[int] = sys.executable if full_python_path else sys.executable.split("/" )[-1] cmd.append(UpperCamelCase__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes _A : Tuple = [] _A : Dict = "" while len(UpperCamelCase__ ) > 0: current_line += f"{cmd.pop(0 )} " if len(UpperCamelCase__ ) == 0 or len(UpperCamelCase__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(UpperCamelCase__ ) _A : Union[str, Any] = "" return "\\\n".join(UpperCamelCase__ ) def _UpperCAmelCase (UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple ): # unwrap multi-line input _A : Union[str, Any] = re.sub(r"[\\\n]+" , " " , args.base_cmd ) # remove --output_dir if any and set our own _A : int = re.sub("--output_dir\s+[^\s]+" , "" , args.base_cmd ) args.base_cmd += f" --output_dir {output_dir}" # ensure we have --overwrite_output_dir _A : int = re.sub("--overwrite_output_dir\s+" , "" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _UpperCAmelCase (UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , ) _A : Dict = subprocess.run(UpperCamelCase__ , capture_output=UpperCamelCase__ , text=UpperCamelCase__ ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams _A : Tuple = variation.replace(" " , "-" ) with open(Path(UpperCamelCase__ ) / f"log.{prefix}.stdout.txt" , "w" ) as f: f.write(result.stdout ) with open(Path(UpperCamelCase__ ) / f"log.{prefix}.stderr.txt" , "w" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("failed" ) return {target_metric_key: nan} with io.open(f"{output_dir}/all_results.json" , "r" , encoding="utf-8" ) as f: _A : List[str] = json.load(UpperCamelCase__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _UpperCAmelCase (UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Any , ): _A : Union[str, Any] = [] _A : Optional[int] = [] _A : Any = f"{id}: {variation:<{longest_variation_len}}" _A : Dict = f"{preamble}: " _A : Union[str, Any] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(UpperCamelCase__ ) , desc=UpperCamelCase__ , leave=UpperCamelCase__ ): _A : Optional[Any] = process_run_single( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _A : Optional[Any] = single_run_metrics[target_metric_key] if not math.isnan(UpperCamelCase__ ): metrics.append(UpperCamelCase__ ) results.append(UpperCamelCase__ ) outcome += "✓" else: outcome += "✘" _A : str = f"\33[2K\r{outcome}" if len(UpperCamelCase__ ) > 0: _A : List[str] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} _A : Any = round(mean_metrics[target_metric_key] , 2 ) _A : Tuple = f"{outcome} {mean_target}" if len(UpperCamelCase__ ) > 1: results_str += f" {tuple(round(UpperCamelCase__ , 2 ) for x in results )}" print(UpperCamelCase__ ) _A : Optional[int] = variation return mean_metrics else: print(UpperCamelCase__ ) return {variation_key: variation, target_metric_key: nan} def _UpperCAmelCase (): _A : int = torch.cuda.get_device_properties(torch.device("cuda" ) ) return f"\nDatetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n" def _UpperCAmelCase (UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict ): _A : Any = pd.DataFrame(UpperCamelCase__ ) _A : List[str] = "variation" _A : List[Any] = "diff_%" _A : int = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan _A : int = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(UpperCamelCase__ ): # as a fallback, use the minimal value as the sentinel _A : List[str] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(UpperCamelCase__ ): _A : Optional[Any] = df.apply( lambda UpperCamelCase__ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="columns" , ) # re-order columns _A : Union[str, Any] = [variation_key, target_metric_key, diff_key, *report_metric_keys] _A : Any = df.reindex(UpperCamelCase__ , axis="columns" ) # reorder cols # capitalize _A : Tuple = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible _A : List[str] = df.rename(lambda UpperCamelCase__ : c.replace("_" , "<br>" ) , axis="columns" ) _A : Union[str, Any] = df.rename(lambda UpperCamelCase__ : c.replace("_" , "\n" ) , axis="columns" ) _A : Optional[int] = ["", "Copy between the cut-here-lines and paste as is to github or a forum"] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=UpperCamelCase__ , floatfmt=".2f" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=UpperCamelCase__ , floatfmt=".2f" )] print("\n\n".join(UpperCamelCase__ ) ) def _UpperCAmelCase (): _A : int = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=UpperCamelCase__ , type=UpperCamelCase__ , required=UpperCamelCase__ , help="Base cmd" , ) parser.add_argument( "--variations" , default=UpperCamelCase__ , type=UpperCamelCase__ , nargs="+" , required=UpperCamelCase__ , help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'" , ) parser.add_argument( "--base-variation" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="Baseline variation to compare to. if None the minimal target value will be used to compare against" , ) parser.add_argument( "--target-metric-key" , default=UpperCamelCase__ , type=UpperCamelCase__ , required=UpperCamelCase__ , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=UpperCamelCase__ , help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples" , ) parser.add_argument( "--repeat-times" , default=1 , type=UpperCamelCase__ , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=UpperCamelCase__ , help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked" , ) parser.add_argument( "--verbose" , default=UpperCamelCase__ , action="store_true" , help="Whether to show the outputs of each run or just the benchmark progress" , ) _A : int = parser.parse_args() _A : Union[str, Any] = args.output_dir Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) _A : Tuple = get_base_command(UpperCamelCase__ , UpperCamelCase__ ) # split each dimension into its --foo variations _A : Dict = [list(map(str.strip , re.split(r"\|" , UpperCamelCase__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty _A : Union[str, Any] = list(map(str.strip , map(" ".join , itertools.product(*UpperCamelCase__ ) ) ) ) _A : Union[str, Any] = max(len(UpperCamelCase__ ) for x in variations ) # split wanted keys _A : str = args.report_metric_keys.split() # capture prints into a log file for convenience _A : Optional[int] = f"benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S' )}.txt" print(f"\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt" ) print(f"and this script's output is also piped into {report_fn}" ) _A : Tuple = Tee(UpperCamelCase__ ) print(f"\n*** Running {len(UpperCamelCase__ )} benchmarks:" ) print(f"Base command: {' '.join(UpperCamelCase__ )}" ) _A : str = "variation" _A : Union[str, Any] = [] for id, variation in enumerate(tqdm(UpperCamelCase__ , desc="Total completion: " , leave=UpperCamelCase__ ) ): _A : Dict = base_cmd + variation.split() results.append( process_run( id + 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , args.target_metric_key , UpperCamelCase__ , args.repeat_times , UpperCamelCase__ , args.verbose , ) ) process_results(UpperCamelCase__ , args.target_metric_key , UpperCamelCase__ , args.base_variation , UpperCamelCase__ ) if __name__ == "__main__": main()
11
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets lowerCamelCase_ = datasets.logging.get_logger(__name__) lowerCamelCase_ = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = "{COMET}: A Neural Framework for {MT} Evaluation", author = "Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", month = nov, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.emnlp-main.213", pages = "2685--2702", } ''' lowerCamelCase_ = '''\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. ''' lowerCamelCase_ = ''' COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric(\'comet\') >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."] >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"] >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results["scores"]]) [0.19, 0.92] ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): """simple docstring""" def lowerCAmelCase ( self : int ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://unbabel.github.io/COMET/html/index.html" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "sources": datasets.Value("string" , id="sequence" ), "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/Unbabel/COMET"] , reference_urls=[ "https://github.com/Unbabel/COMET", "https://www.aclweb.org/anthology/2020.emnlp-main.213/", "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6", ] , ) def lowerCAmelCase ( self : Any , __UpperCAmelCase : str ): '''simple docstring''' if self.config_name == "default": _A = comet.load_from_checkpoint(comet.download_model("wmt20-comet-da" ) ) else: _A = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def lowerCAmelCase ( self : str , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : int=False ): '''simple docstring''' if gpus is None: _A = 1 if torch.cuda.is_available() else 0 _A = {"src": sources, "mt": predictions, "ref": references} _A = [dict(zip(__UpperCAmelCase , __UpperCAmelCase ) ) for t in zip(*data.values() )] _A , _A = self.scorer.predict(__UpperCAmelCase , gpus=__UpperCAmelCase , progress_bar=__UpperCAmelCase ) return {"mean_score": mean_score, "scores": scores}
79
0
"""simple docstring""" from collections.abc import Sequence from queue import Queue class lowerCAmelCase : '''simple docstring''' def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None ) -> Dict: SCREAMING_SNAKE_CASE = start SCREAMING_SNAKE_CASE = end SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = (start + end) // 2 SCREAMING_SNAKE_CASE = left SCREAMING_SNAKE_CASE = right def __repr__( self ) -> Tuple: return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class lowerCAmelCase : '''simple docstring''' def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Any: SCREAMING_SNAKE_CASE = collection SCREAMING_SNAKE_CASE = function if self.collection: SCREAMING_SNAKE_CASE = self._build_tree(0 , len(lowerCAmelCase__ ) - 1 ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: self._update_tree(self.root , lowerCAmelCase__ , lowerCAmelCase__ ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: return self._query_range(self.root , lowerCAmelCase__ , lowerCAmelCase__ ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: if start == end: return SegmentTreeNode(lowerCAmelCase__ , lowerCAmelCase__ , self.collection[start] ) SCREAMING_SNAKE_CASE = (start + end) // 2 SCREAMING_SNAKE_CASE = self._build_tree(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = self._build_tree(mid + 1 , lowerCAmelCase__ ) return SegmentTreeNode(lowerCAmelCase__ , lowerCAmelCase__ , self.fn(left.val , right.val ) , lowerCAmelCase__ , lowerCAmelCase__ ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: if node.start == i and node.end == i: SCREAMING_SNAKE_CASE = val return if i <= node.mid: self._update_tree(node.left , lowerCAmelCase__ , lowerCAmelCase__ ) else: self._update_tree(node.right , lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = self.fn(node.left.val , node.right.val ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: 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 , lowerCAmelCase__ , lowerCAmelCase__ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , lowerCAmelCase__ , node.mid ) , self._query_range(node.right , node.mid + 1 , lowerCAmelCase__ ) , ) else: # range in right child tree return self._query_range(node.right , lowerCAmelCase__ , lowerCAmelCase__ ) def __A ( self ) -> Union[str, Any]: if self.root is not None: SCREAMING_SNAKE_CASE = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE = 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) __UpperCamelCase = 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()
38
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> bool: SCREAMING_SNAKE_CASE = int(number**0.5 ) return number == sq * sq def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> tuple[int, int]: SCREAMING_SNAKE_CASE = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den SCREAMING_SNAKE_CASE = x_den * y_den * z_den SCREAMING_SNAKE_CASE = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) top //= hcf bottom //= hcf return top, bottom def lowercase (SCREAMING_SNAKE_CASE_ : int = 35 ) -> int: SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = Fraction(0 ) SCREAMING_SNAKE_CASE = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 SCREAMING_SNAKE_CASE = x_num * y_den + x_den * y_num SCREAMING_SNAKE_CASE = x_den * y_den SCREAMING_SNAKE_CASE = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=2 SCREAMING_SNAKE_CASE = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) SCREAMING_SNAKE_CASE = x_den * x_den * y_den * y_den if is_sq(SCREAMING_SNAKE_CASE_ ) and is_sq(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=-1 SCREAMING_SNAKE_CASE = x_num * y_num SCREAMING_SNAKE_CASE = x_den * y_num + x_num * y_den SCREAMING_SNAKE_CASE = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=2 SCREAMING_SNAKE_CASE = x_num * x_num * y_num * y_num SCREAMING_SNAKE_CASE = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(SCREAMING_SNAKE_CASE_ ) and is_sq(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) for num, den in unique_s: total += Fraction(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
38
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_bigbird_pegasus': [ 'BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BigBirdPegasusConfig', 'BigBirdPegasusOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST', 'BigBirdPegasusForCausalLM', 'BigBirdPegasusForConditionalGeneration', 'BigBirdPegasusForQuestionAnswering', 'BigBirdPegasusForSequenceClassification', 'BigBirdPegasusModel', 'BigBirdPegasusPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
175
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 ( snake_case_ , unittest.TestCase ): lowercase = XLMTokenizer lowercase = False def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase_ : List[Any] = [ '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>', ] UpperCamelCase_ : str = dict(zip(snake_case , range(len(snake_case ) ) ) ) UpperCamelCase_ : Tuple = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] UpperCamelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(snake_case ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : Union[str, Any] ) -> int: """simple docstring""" UpperCamelCase_ : Tuple = 'lower newer' UpperCamelCase_ : Optional[int] = 'lower newer' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ : int = XLMTokenizer(self.vocab_file , self.merges_file ) UpperCamelCase_ : List[str] = 'lower' UpperCamelCase_ : Optional[int] = ['low', 'er</w>'] UpperCamelCase_ : Optional[Any] = tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case , snake_case ) UpperCamelCase_ : List[Any] = tokens + ['<unk>'] UpperCamelCase_ : int = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , snake_case ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : int = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) UpperCamelCase_ : int = tokenizer.encode('sequence builders' , add_special_tokens=snake_case ) UpperCamelCase_ : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=snake_case ) UpperCamelCase_ : Tuple = tokenizer.build_inputs_with_special_tokens(snake_case ) UpperCamelCase_ : Any = tokenizer.build_inputs_with_special_tokens(snake_case , snake_case ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
175
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: _UpperCamelCase : Union[str, Any] = '''ZinengTang/tvlt-base''' _UpperCamelCase : List[Any] = tempfile.mkdtemp() def __SCREAMING_SNAKE_CASE ( self : List[Any] , **__a : Union[str, Any] ) -> str: return TvltImageProcessor.from_pretrained(self.checkpoint , **a_ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , **__a : Dict ) -> Optional[Any]: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **a_ ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : List[str] = self.get_feature_extractor() _UpperCamelCase : str = TvltProcessor(image_processor=a_ , feature_extractor=a_ ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase : Tuple = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , a_ ) self.assertIsInstance(processor.image_processor , a_ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Optional[Any] = self.get_image_processor() _UpperCamelCase : List[Any] = self.get_feature_extractor() _UpperCamelCase : Optional[int] = TvltProcessor(image_processor=a_ , feature_extractor=a_ ) _UpperCamelCase : Dict = np.ones([1_2000] ) _UpperCamelCase : Dict = feature_extractor(a_ , return_tensors="np" ) _UpperCamelCase : Optional[int] = processor(audio=a_ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Any: _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : Optional[int] = self.get_feature_extractor() _UpperCamelCase : Tuple = TvltProcessor(image_processor=a_ , feature_extractor=a_ ) _UpperCamelCase : str = np.ones([3, 224, 224] ) _UpperCamelCase : List[str] = image_processor(a_ , return_tensors="np" ) _UpperCamelCase : Optional[int] = processor(images=a_ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : Dict = self.get_image_processor() _UpperCamelCase : int = self.get_feature_extractor() _UpperCamelCase : List[Any] = TvltProcessor(image_processor=a_ , feature_extractor=a_ ) _UpperCamelCase : Union[str, Any] = np.ones([1_2000] ) _UpperCamelCase : Optional[int] = np.ones([3, 224, 224] ) _UpperCamelCase : Union[str, Any] = processor(audio=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(a_ ): processor() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: _UpperCamelCase : str = self.get_image_processor() _UpperCamelCase : List[str] = self.get_feature_extractor() _UpperCamelCase : int = TvltProcessor(image_processor=a_ , feature_extractor=a_ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
352
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Optional[Any]: """simple docstring""" with open(lowercase_ ) as metadata_file: _UpperCamelCase : Dict = json.load(lowercase_ ) _UpperCamelCase : str = LukeConfig(use_entity_aware_attention=lowercase_ ,**metadata["model_config"] ) # Load in the weights from the checkpoint_path _UpperCamelCase : str = torch.load(lowercase_ ,map_location="cpu" )["module"] # Load the entity vocab file _UpperCamelCase : Dict = load_original_entity_vocab(lowercase_ ) # add an entry for [MASK2] _UpperCamelCase : Any = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 _UpperCamelCase : Optional[Any] = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks _UpperCamelCase : Dict = AddedToken("<ent>" ,lstrip=lowercase_ ,rstrip=lowercase_ ) _UpperCamelCase : Union[str, Any] = AddedToken("<ent2>" ,lstrip=lowercase_ ,rstrip=lowercase_ ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(lowercase_ ) with open(os.path.join(lowercase_ ,"tokenizer_config.json" ) ,"r" ) as f: _UpperCamelCase : Tuple = json.load(lowercase_ ) _UpperCamelCase : Optional[int] = "MLukeTokenizer" with open(os.path.join(lowercase_ ,"tokenizer_config.json" ) ,"w" ) as f: json.dump(lowercase_ ,lowercase_ ) with open(os.path.join(lowercase_ ,MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) ,"w" ) as f: json.dump(lowercase_ ,lowercase_ ) _UpperCamelCase : int = MLukeTokenizer.from_pretrained(lowercase_ ) # Initialize the embeddings of the special tokens _UpperCamelCase : List[Any] = tokenizer.convert_tokens_to_ids(["@"] )[0] _UpperCamelCase : str = tokenizer.convert_tokens_to_ids(["#"] )[0] _UpperCamelCase : Union[str, Any] = state_dict["embeddings.word_embeddings.weight"] _UpperCamelCase : Optional[Any] = word_emb[ent_init_index].unsqueeze(0 ) _UpperCamelCase : List[str] = word_emb[enta_init_index].unsqueeze(0 ) _UpperCamelCase : Union[str, Any] = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: _UpperCamelCase : Optional[Any] = state_dict[bias_name] _UpperCamelCase : List[Any] = decoder_bias[ent_init_index].unsqueeze(0 ) _UpperCamelCase : Tuple = decoder_bias[enta_init_index].unsqueeze(0 ) _UpperCamelCase : Optional[int] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _UpperCamelCase : Tuple = F'''encoder.layer.{layer_index}.attention.self.''' _UpperCamelCase : List[Any] = state_dict[prefix + matrix_name] _UpperCamelCase : str = state_dict[prefix + matrix_name] _UpperCamelCase : Any = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _UpperCamelCase : Any = state_dict["entity_embeddings.entity_embeddings.weight"] _UpperCamelCase : Tuple = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCamelCase : int = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' _UpperCamelCase : int = state_dict["entity_predictions.bias"] _UpperCamelCase : Dict = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCamelCase : List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) _UpperCamelCase : str = LukeForMaskedLM(config=lowercase_ ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) _UpperCamelCase : List[str] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): _UpperCamelCase : Union[str, Any] = state_dict[key] else: _UpperCamelCase : Dict = state_dict[key] _UpperCamelCase, _UpperCamelCase : Optional[Any] = model.load_state_dict(lowercase_ ,strict=lowercase_ ) if set(lowercase_ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(lowercase_ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs _UpperCamelCase : List[Any] = MLukeTokenizer.from_pretrained(lowercase_ ,task="entity_classification" ) _UpperCamelCase : Dict = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." _UpperCamelCase : Optional[Any] = (0, 9) _UpperCamelCase : int = tokenizer(lowercase_ ,entity_spans=[span] ,return_tensors="pt" ) _UpperCamelCase : List[str] = model(**lowercase_ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCamelCase : Tuple = torch.Size((1, 33, 768) ) _UpperCamelCase : List[Any] = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] ,lowercase_ ,atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCamelCase : Tuple = torch.Size((1, 1, 768) ) _UpperCamelCase : List[Any] = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] ,lowercase_ ,atol=1e-4 ): raise ValueError # Verify masked word/entity prediction _UpperCamelCase : List[Any] = MLukeTokenizer.from_pretrained(lowercase_ ) _UpperCamelCase : int = "Tokyo is the capital of <mask>." _UpperCamelCase : List[Any] = (24, 30) _UpperCamelCase : Any = tokenizer(lowercase_ ,entity_spans=[span] ,return_tensors="pt" ) _UpperCamelCase : Optional[Any] = model(**lowercase_ ) _UpperCamelCase : int = encoding["input_ids"][0].tolist() _UpperCamelCase : List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) _UpperCamelCase : List[str] = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(lowercase_ ) _UpperCamelCase : Union[str, Any] = outputs.entity_logits[0][0].argmax().item() _UpperCamelCase : Tuple = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(lowercase_ ) ) model.save_pretrained(lowercase_ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : List[str] = ["[MASK]", "[PAD]", "[UNK]"] _UpperCamelCase : Tuple = [json.loads(lowercase_ ) for line in open(lowercase_ )] _UpperCamelCase : List[str] = {} for entry in data: _UpperCamelCase : Any = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: _UpperCamelCase : Dict = entity_id break _UpperCamelCase : Dict = F'''{language}:{entity_name}''' _UpperCamelCase : str = entity_id return new_mapping if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) lowerCamelCase__ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
310
0
from __future__ import annotations A_ :int = tuple[int, int, int] A_ :Tuple = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase A_ :int = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- A_ :Tuple = '''EGZWVONAHDCLFQMSIPJBYUKXTR''' A_ :int = '''FOBHMDKEXQNRAULPGSJVTYICZW''' A_ :Any = '''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- A_ :Optional[int] = { '''A''': '''N''', '''N''': '''A''', '''B''': '''O''', '''O''': '''B''', '''C''': '''P''', '''P''': '''C''', '''D''': '''Q''', '''Q''': '''D''', '''E''': '''R''', '''R''': '''E''', '''F''': '''S''', '''S''': '''F''', '''G''': '''T''', '''T''': '''G''', '''H''': '''U''', '''U''': '''H''', '''I''': '''V''', '''V''': '''I''', '''J''': '''W''', '''W''': '''J''', '''K''': '''X''', '''X''': '''K''', '''L''': '''Y''', '''Y''': '''L''', '''M''': '''Z''', '''Z''': '''M''', } # -------------------------- extra rotors -------------------------- A_ :List[str] = '''RMDJXFUWGISLHVTCQNKYPBEZOA''' A_ :List[str] = '''SGLCPQWZHKXAREONTFBVIYJUDM''' A_ :Union[str, Any] = '''HVSICLTYKQUBXDWAJZOMFGPREN''' A_ :Optional[Any] = '''RZWQHFMVDBKICJLNTUXAGYPSOE''' A_ :List[Any] = '''LFKIJODBEGAMQPXVUHYSTCZRWN''' A_ :Dict = '''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def A ( a_ ,a_ ,a_ ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(a_ ) )) < 3: __UpperCamelCase : Optional[int] =F'Please use 3 unique rotors (not {unique_rotsel})' raise Exception(a_ ) # Checks if rotor positions are valid __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Optional[Any] =rotpos if not 0 < rotorposa <= len(a_ ): __UpperCamelCase : Optional[Any] =F'First rotor position is not within range of 1..26 ({rotorposa}' raise ValueError(a_ ) if not 0 < rotorposa <= len(a_ ): __UpperCamelCase : int =F'Second rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(a_ ) if not 0 < rotorposa <= len(a_ ): __UpperCamelCase : Any =F'Third rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(a_ ) # Validates string and returns dict __UpperCamelCase : Dict =_plugboard(a_ ) return rotpos, rotsel, pbdict def A ( a_ ) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(a_ ,a_ ): __UpperCamelCase : Dict =F'Plugboard setting isn\'t type string ({type(a_ )})' raise TypeError(a_ ) elif len(a_ ) % 2 != 0: __UpperCamelCase : Any =F'Odd number of symbols ({len(a_ )})' raise Exception(a_ ) elif pbstring == "": return {} pbstring.replace(' ' ,'' ) # Checks if all characters are unique __UpperCamelCase : List[str] =set() for i in pbstring: if i not in abc: __UpperCamelCase : List[Any] =F'\'{i}\' not in list of symbols' raise Exception(a_ ) elif i in tmppbl: __UpperCamelCase : Optional[Any] =F'Duplicate symbol ({i})' raise Exception(a_ ) else: tmppbl.add(a_ ) del tmppbl # Created the dictionary __UpperCamelCase : Optional[Any] ={} for j in range(0 ,len(a_ ) - 1 ,2 ): __UpperCamelCase : Union[str, Any] =pbstring[j + 1] __UpperCamelCase : List[Any] =pbstring[j] return pb def A ( a_ ,a_ ,a_ = (rotora, rotora, rotora) ,a_ = "" ,) -> str: __UpperCamelCase : Optional[Any] =text.upper() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : List[str] =_validator( a_ ,a_ ,plugb.upper() ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Tuple =rotor_position __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : int =rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 __UpperCamelCase : Tuple =[] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: __UpperCamelCase : str =plugboard[symbol] # rotor ra -------------------------- __UpperCamelCase : Any =abc.index(a_ ) + rotorposa __UpperCamelCase : Tuple =rotora[index % len(a_ )] # rotor rb -------------------------- __UpperCamelCase : Any =abc.index(a_ ) + rotorposa __UpperCamelCase : Dict =rotora[index % len(a_ )] # rotor rc -------------------------- __UpperCamelCase : Dict =abc.index(a_ ) + rotorposa __UpperCamelCase : str =rotora[index % len(a_ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher __UpperCamelCase : List[str] =reflector[symbol] # 2nd rotors __UpperCamelCase : Union[str, Any] =abc[rotora.index(a_ ) - rotorposa] __UpperCamelCase : Optional[Any] =abc[rotora.index(a_ ) - rotorposa] __UpperCamelCase : Optional[int] =abc[rotora.index(a_ ) - rotorposa] # 2nd plugboard if symbol in plugboard: __UpperCamelCase : Any =plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(a_ ): __UpperCamelCase : int =0 rotorposa += 1 if rotorposa >= len(a_ ): __UpperCamelCase : List[Any] =0 rotorposa += 1 if rotorposa >= len(a_ ): __UpperCamelCase : Dict =0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(a_ ) return "".join(a_ ) if __name__ == "__main__": A_ :Dict = '''This is my Python script that emulates the Enigma machine from WWII.''' A_ :Tuple = (1, 1, 1) A_ :Any = '''pictures''' A_ :Union[str, Any] = (rotora, rotora, rotora) A_ :Dict = enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
71
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __A ( a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : str =DDIMPipeline UpperCamelCase__ : List[Any] =UNCONDITIONAL_IMAGE_GENERATION_PARAMS UpperCamelCase__ : Tuple =PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """latents""", """callback""", """callback_steps""", } UpperCamelCase__ : Tuple =UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS UpperCamelCase__ : Any =False def __lowercase ( self ): """simple docstring""" torch.manual_seed(0 ) __UpperCamelCase : Optional[int] =UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) __UpperCamelCase : int =DDIMScheduler() __UpperCamelCase : Optional[int] ={'unet': unet, 'scheduler': scheduler} return components def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__=0 ): """simple docstring""" if str(lowerCamelCase__ ).startswith('mps' ): __UpperCamelCase : str =torch.manual_seed(lowerCamelCase__ ) else: __UpperCamelCase : Optional[int] =torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) __UpperCamelCase : Tuple ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Any ='cpu' __UpperCamelCase : Optional[Any] =self.get_dummy_components() __UpperCamelCase : Tuple =self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =self.get_dummy_inputs(lowerCamelCase__ ) __UpperCamelCase : int =pipe(**lowerCamelCase__ ).images __UpperCamelCase : Dict =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) __UpperCamelCase : Tuple =np.array( [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] ) __UpperCamelCase : Tuple =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase__ , 1E-3 ) def __lowercase ( self ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def __lowercase ( self ): """simple docstring""" super().test_save_load_local(expected_max_difference=3E-3 ) def __lowercase ( self ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=3E-3 ) def __lowercase ( self ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __A ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" __UpperCamelCase : str ='google/ddpm-cifar10-32' __UpperCamelCase : str =UNetaDModel.from_pretrained(lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =DDIMScheduler() __UpperCamelCase : List[Any] =DDIMPipeline(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ ) ddim.to(lowerCamelCase__ ) ddim.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Optional[int] =torch.manual_seed(0 ) __UpperCamelCase : List[str] =ddim(generator=lowerCamelCase__ , eta=0.0 , output_type='numpy' ).images __UpperCamelCase : Union[str, Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase : str =np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] ='google/ddpm-ema-bedroom-256' __UpperCamelCase : Any =UNetaDModel.from_pretrained(lowerCamelCase__ ) __UpperCamelCase : int =DDIMScheduler.from_pretrained(lowerCamelCase__ ) __UpperCamelCase : Dict =DDIMPipeline(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ ) ddpm.to(lowerCamelCase__ ) ddpm.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Tuple =torch.manual_seed(0 ) __UpperCamelCase : Union[str, Any] =ddpm(generator=lowerCamelCase__ , output_type='numpy' ).images __UpperCamelCase : Tuple =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCamelCase : Optional[Any] =np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
71
1
'''simple docstring''' from __future__ import annotations lowerCamelCase : Optional[Any] = "Muhammad Umer Farooq" lowerCamelCase : List[Any] = "MIT" lowerCamelCase : str = "1.0.0" lowerCamelCase : str = "Muhammad Umer Farooq" lowerCamelCase : Union[str, Any] = "contact@muhammadumerfarooq.me" lowerCamelCase : str = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class A__ ( A__ ): def __init__( self : int , _a : str ) -> None: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =domain def A ( self : Optional[int] , _a : str , _a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _SCREAMING_SNAKE_CASE =parse.urljoin(self.domain , _a ) self.urls.append(_a ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" return ".".join(get_sub_domain_name(_UpperCamelCase ).split('.' )[-2:] ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" return parse.urlparse(_UpperCamelCase ).netloc def _lowerCAmelCase ( _UpperCamelCase : str = "https://github.com" ) -> list[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =get_domain_name(_UpperCamelCase ) # Initialize the parser _SCREAMING_SNAKE_CASE =Parser(_UpperCamelCase ) try: # Open URL _SCREAMING_SNAKE_CASE =requests.get(_UpperCamelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _SCREAMING_SNAKE_CASE =set() for link in parser.urls: # open URL. # read = requests.get(link) try: _SCREAMING_SNAKE_CASE =requests.get(_UpperCamelCase ) # Get the valid email. _SCREAMING_SNAKE_CASE =re.findall('[a-zA-Z0-9]+@' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCamelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase : Optional[int] = emails_from_url("https://github.com") print(f'''{len(emails)} emails found:''') print("\n".join(sorted(emails)))
114
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Tuple = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : str = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys lowerCamelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
114
1
'''simple docstring''' from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def snake_case_ ( _lowerCAmelCase : float , _lowerCAmelCase : float , _lowerCAmelCase : bool = False ) -> list[float]: if radian_mode: return [magnitude * cos(_lowerCAmelCase ), magnitude * sin(_lowerCAmelCase )] return [magnitude * cos(radians(_lowerCAmelCase ) ), magnitude * sin(radians(_lowerCAmelCase ) )] def snake_case_ ( _lowerCAmelCase : NDArray[floataa] , _lowerCAmelCase : NDArray[floataa] , _lowerCAmelCase : float = 10**-1 ) -> bool: UpperCAmelCase : NDArray[floataa] = cross(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase : float = sum(_lowerCAmelCase ) return abs(_lowerCAmelCase ) < eps if __name__ == "__main__": # Test to check if it works UpperCamelCase__: List[Any] = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCamelCase__: NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCamelCase__: Optional[Any] = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCamelCase__: int = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCamelCase__: List[Any] = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) UpperCamelCase__: List[str] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
23
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType A_ : Dict = logging.get_logger(__name__) A_ : Any = { "microsoft/deberta-v2-xlarge": "https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json", "microsoft/deberta-v2-xxlarge": "https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json", "microsoft/deberta-v2-xlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json" ), "microsoft/deberta-v2-xxlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json" ), } class lowerCamelCase (A__ ): lowerCamelCase__ : Tuple = 'deberta-v2' def __init__( self : Any , __UpperCAmelCase : Optional[Any]=1_2_8_1_0_0 , __UpperCAmelCase : Optional[Any]=1_5_3_6 , __UpperCAmelCase : List[Any]=2_4 , __UpperCAmelCase : str=2_4 , __UpperCAmelCase : Optional[int]=6_1_4_4 , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : Optional[Any]=5_1_2 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : Any=1e-7 , __UpperCAmelCase : Tuple=False , __UpperCAmelCase : Any=-1 , __UpperCAmelCase : Union[str, Any]=0 , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Optional[Any]=0 , __UpperCAmelCase : Union[str, Any]="gelu" , **__UpperCAmelCase : Any , ) -> Union[str, Any]: super().__init__(**__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = relative_attention SCREAMING_SNAKE_CASE__ = max_relative_positions SCREAMING_SNAKE_CASE__ = pad_token_id SCREAMING_SNAKE_CASE__ = position_biased_input # Backwards compatibility if type(__UpperCAmelCase ) == str: SCREAMING_SNAKE_CASE__ = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE__ = pos_att_type SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = kwargs.get("""pooler_hidden_size""" , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = pooler_dropout SCREAMING_SNAKE_CASE__ = pooler_hidden_act class lowerCamelCase (A__ ): @property def SCREAMING_SNAKE_CASE ( self : Any ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return 1_2 def SCREAMING_SNAKE_CASE ( self : Tuple , __UpperCAmelCase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional["TensorType"] = None , __UpperCAmelCase : int = 3 , __UpperCAmelCase : int = 4_0 , __UpperCAmelCase : int = 4_0 , __UpperCAmelCase : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: SCREAMING_SNAKE_CASE__ = super().generate_dummy_inputs(preprocessor=__UpperCAmelCase , framework=__UpperCAmelCase ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
165
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = { 'configuration_roformer': ['ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoFormerConfig', 'RoFormerOnnxConfig'], 'tokenization_roformer': ['RoFormerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['RoFormerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoFormerForCausalLM', 'RoFormerForMaskedLM', 'RoFormerForMultipleChoice', 'RoFormerForQuestionAnswering', 'RoFormerForSequenceClassification', 'RoFormerForTokenClassification', 'RoFormerLayer', 'RoFormerModel', 'RoFormerPreTrainedModel', 'load_tf_weights_in_roformer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRoFormerForCausalLM', 'TFRoFormerForMaskedLM', 'TFRoFormerForMultipleChoice', 'TFRoFormerForQuestionAnswering', 'TFRoFormerForSequenceClassification', 'TFRoFormerForTokenClassification', 'TFRoFormerLayer', 'TFRoFormerModel', 'TFRoFormerPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxRoFormerForMaskedLM', 'FlaxRoFormerForMultipleChoice', 'FlaxRoFormerForQuestionAnswering', 'FlaxRoFormerForSequenceClassification', 'FlaxRoFormerForTokenClassification', 'FlaxRoFormerModel', 'FlaxRoFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
302
"""simple docstring""" # Copyright 2023 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. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase_ = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
302
1
import math def lowerCamelCase__ ( snake_case_ : int ) -> int: if not isinstance(snake_case_ , snake_case_ ): __snake_case = f"""Input value of [number={number}] must be an integer""" raise TypeError(snake_case_ ) if number < 1: __snake_case = f"""Input value of [number={number}] must be > 0""" raise ValueError(snake_case_ ) elif number == 1: return 3 elif number == 2: return 5 else: __snake_case = int(math.log(number // 3 , 2 ) ) + 2 __snake_case = [3, 5] __snake_case = 2 __snake_case = 3 for block in range(1 , snake_case_ ): for _ in range(snake_case_ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): snake_case_ = 0 try: snake_case_ = proth(number) except ValueError: print(F'ValueError: there is no {number}th Proth number') continue print(F'The {number}th Proth number: {value}')
24
import os import pytest from transformers.dynamic_module_utils import get_imports snake_case_ = '\nimport os\n' snake_case_ = '\ndef foo():\n import os\n return False\n' snake_case_ = '\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n' snake_case_ = '\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n' snake_case_ = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n' snake_case_ = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('''case''' , snake_case_ ) def lowerCamelCase__ ( snake_case_ : str , snake_case_ : Optional[int] ) -> Dict: __snake_case = os.path.join(snake_case_ , '''test_file.py''' ) with open(snake_case_ , '''w''' ) as _tmp_file: _tmp_file.write(snake_case_ ) __snake_case = get_imports(snake_case_ ) assert parsed_imports == ["os"]
24
1
from torch import nn class snake_case_ ( nn.Module ): def __init__( self : List[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple ) -> str: super().__init__() lowercase__ : List[str] = class_size lowercase__ : Optional[int] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) lowercase__ : Union[str, Any] = nn.Linear(lowercase_ , lowercase_ ) def __UpperCamelCase ( self : Dict , lowercase_ : Optional[int] ) -> Optional[Any]: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) lowercase__ : str = self.mlp(lowercase_ ) return logits
333
def lowercase_ ( _lowerCamelCase : int = 10 , _lowerCamelCase : int = 1000 , _lowerCamelCase : bool = True): assert ( isinstance(_lowerCamelCase , _lowerCamelCase) and isinstance(_lowerCamelCase , _lowerCamelCase) and isinstance(_lowerCamelCase , _lowerCamelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : int): return int((number_a + number_a) / 2) def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int): assert ( isinstance(_lowerCamelCase , _lowerCamelCase) and isinstance(_lowerCamelCase , _lowerCamelCase) and isinstance(_lowerCamelCase , _lowerCamelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(_lowerCamelCase : int) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") lowercase__ : Optional[int] = lower lowercase__ : List[Any] = higher lowercase__ : Dict = [] while True: lowercase__ : Any = get_avg(_lowerCamelCase , _lowerCamelCase) last_numbers.append(_lowerCamelCase) if answer(_lowerCamelCase) == "low": lowercase__ : List[str] = number elif answer(_lowerCamelCase) == "high": lowercase__ : Optional[int] = number else: break print(f'''guess the number : {last_numbers[-1]}''') print(f'''details : {last_numbers!s}''') def lowercase_ ( ): lowercase__ : Tuple = int(input("Enter lower value : ").strip()) lowercase__ : Optional[int] = int(input("Enter high value : ").strip()) lowercase__ : Optional[Any] = int(input("Enter value to guess : ").strip()) guess_the_number(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) if __name__ == "__main__": main()
333
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): __lowerCAmelCase : Tuple =get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right __lowerCAmelCase : Any =1_2_8_0_2_2 __lowerCAmelCase : List[Any] =1_2_8_0_2_8 @require_sentencepiece class _lowercase ( A__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = MaMaaaTokenizer SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : Dict = False SCREAMING_SNAKE_CASE__ : Dict = True def __magic_name__( self :Dict ) -> Any: super().setUp() __SCREAMING_SNAKE_CASE : int = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] __SCREAMING_SNAKE_CASE : Any = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(self.tmpdirname ) save_json(lowerCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(lowerCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) __SCREAMING_SNAKE_CASE : List[str] = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__( self :Union[str, Any] , **lowerCAmelCase__ :List[str] ) -> List[str]: return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def __magic_name__( self :str , lowerCAmelCase__ :Tuple ) -> Any: return ( "This is a test", "This is a test", ) def __magic_name__( self :List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''</s>''' __SCREAMING_SNAKE_CASE : Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ ) def __magic_name__( self :Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Any = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(lowerCAmelCase__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def __magic_name__( self :Optional[Any] ) -> int: pass def __magic_name__( self :int ) -> List[Any]: __SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [2, 3, 4, 5, 6] , ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(lowerCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) __SCREAMING_SNAKE_CASE : int = tokenizer.convert_tokens_to_string(lowerCAmelCase__ ) self.assertEqual(lowerCAmelCase__ , '''This is a test''' ) @slow def __magic_name__( self :Optional[int] ) -> List[Any]: # fmt: off __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': [[128_022, 110_108, 397, 11, 38_272, 2_247, 124_811, 285, 18_105, 1_586, 207, 7, 39_534, 4_428, 397, 1_019, 18_105, 1_586, 207, 7, 41_337, 16_786, 241, 7, 20_214, 17, 125_690, 10_398, 7, 44_378, 58_069, 68_342, 7_798, 7_343, 11, 299, 33_310, 4, 158, 37_350, 94_077, 4_569, 299, 33_310, 90, 4, 52_840, 290, 4, 31_270, 112, 299, 682, 4, 52_840, 39_953, 14_079, 193, 52_519, 90_894, 17_894, 120_697, 11, 40_445, 551, 17, 1_019, 52_519, 90_894, 17_756, 963, 11, 40_445, 480, 17, 9_792, 1_120, 5_173, 1_393, 6_240, 16_786, 241, 120_996, 28, 1_245, 1_393, 118_240, 11_123, 1_019, 93_612, 2_691, 10_618, 98_058, 120_409, 1_928, 279, 4, 40_683, 367, 178, 207, 1_019, 103, 103_121, 506, 65_296, 5, 2], [128_022, 21_217, 367, 117, 125_450, 128, 719, 7, 7_308, 40, 93_612, 12_669, 1_116, 16_704, 71, 17_785, 3_699, 15_592, 35, 144, 9_584, 241, 11_943, 713, 950, 799, 2_247, 88_427, 150, 149, 118_813, 120_706, 1_019, 106_906, 81_518, 28, 1_224, 22_799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128_022, 1_658, 123_311, 5_155, 5_578, 4_722, 279, 14_947, 2_366, 1_120, 1_197, 14, 1_348, 9_232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase__ , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class _lowercase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '''facebook/m2m100_418M''' SCREAMING_SNAKE_CASE__ : str = [ '''In my opinion, there are two levels of response from the French government.''', '''NSA Affair Emphasizes Complete Lack of Debate on Intelligence''', ] SCREAMING_SNAKE_CASE__ : Dict = [ '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''', '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''', ] # fmt: off SCREAMING_SNAKE_CASE__ : int = [EN_CODE, 593, 1_949, 115_781, 4, 71_586, 4_234, 60_633, 126_233, 432, 123_808, 15_592, 1_197, 117_132, 120_618, 5, 2] @classmethod def __magic_name__( cls :Dict ) -> int: __SCREAMING_SNAKE_CASE : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) __SCREAMING_SNAKE_CASE : Dict = 1 return cls def __magic_name__( self :int ) -> Dict: self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 128_006 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 128_022 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 128_076 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 128_063 ) def __magic_name__( self :Dict ) -> Any: __SCREAMING_SNAKE_CASE : Any = self.tokenizer.get_vocab() self.assertEqual(len(lowerCAmelCase__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , lowerCAmelCase__ ) def __magic_name__( self :str ) -> Tuple: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''en''' __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ ) def __magic_name__( self :Any ) -> Optional[int]: self.assertIn(lowerCAmelCase__ , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = [FR_CODE, 5_364, 82, 8_642, 4, 294, 47, 8, 14_028, 136, 3_286, 9_706, 6, 90_797, 6, 144_012, 162, 88_128, 30_061, 5, 2] # fmt: on __SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase__ ) self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase__ ) def __magic_name__( self :str ) -> int: __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = MaMaaaTokenizer.from_pretrained(lowerCAmelCase__ ) self.assertDictEqual(new_tok.lang_token_to_id , lowerCAmelCase__ ) @require_torch def __magic_name__( self :Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE : Optional[int] = '''en''' __SCREAMING_SNAKE_CASE : Dict = '''fr''' __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: __SCREAMING_SNAKE_CASE : List[str] = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def __magic_name__( self :Dict ) -> Optional[Any]: __SCREAMING_SNAKE_CASE : Dict = '''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) __SCREAMING_SNAKE_CASE : int = '''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def __magic_name__( self :List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE : Optional[int] = '''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) __SCREAMING_SNAKE_CASE : Optional[int] = '''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def __magic_name__( self :Tuple ) -> str: __SCREAMING_SNAKE_CASE : Dict = self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { # en_XX, A, test, EOS '''input_ids''': [[128_022, 58, 4_183, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 128_006, } , )
9
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _lowercase ( A__ ): '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :NestedDataStructureLike[PathLike] , lowerCAmelCase__ :Optional[NamedSplit] = None , lowerCAmelCase__ :Optional[Features] = None , lowerCAmelCase__ :str = None , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :Optional[int] = None , **lowerCAmelCase__ :Optional[int] , ) -> Tuple: super().__init__( lowerCAmelCase__ , split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , num_proc=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : List[str] = path_or_paths if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else {self.split: path_or_paths} __SCREAMING_SNAKE_CASE : int = Text( cache_dir=lowerCAmelCase__ , data_files=lowerCAmelCase__ , features=lowerCAmelCase__ , **lowerCAmelCase__ , ) def __magic_name__( self :Dict ) -> Tuple: # Build iterable dataset if self.streaming: __SCREAMING_SNAKE_CASE : int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : Dict = None __SCREAMING_SNAKE_CASE : Tuple = None self.builder.download_and_prepare( download_config=lowerCAmelCase__ , download_mode=lowerCAmelCase__ , verification_mode=lowerCAmelCase__ , base_path=lowerCAmelCase__ , num_proc=self.num_proc , ) __SCREAMING_SNAKE_CASE : Optional[int] = self.builder.as_dataset( split=self.split , verification_mode=lowerCAmelCase__ , in_memory=self.keep_in_memory ) return dataset
9
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowercase (SCREAMING_SNAKE_CASE_ : List[str] ) -> str: SCREAMING_SNAKE_CASE = os.path.join(args.tf_model_dir , 'parameters.json' ) SCREAMING_SNAKE_CASE = json.loads(open(_UpperCamelCase ).read() ) if not params: raise ValueError( F'It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.' ) if not args.output.endswith('.pt' ): SCREAMING_SNAKE_CASE = args.output + '.pt' SCREAMING_SNAKE_CASE = OrderedDict() with tf.device('/CPU:0' ): SCREAMING_SNAKE_CASE = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE = reader.get_tensor(_UpperCamelCase ).astype(np.floataa ) if key_name.endswith('/adam_m' ) or key_name.endswith('/adam_v' ): continue if key_name.startswith('pasts/' ): if key_name.startswith('pasts/mlp' ): SCREAMING_SNAKE_CASE = int(key_name[9] ) elif key_name.startswith('pasts/out' ): SCREAMING_SNAKE_CASE = 8 SCREAMING_SNAKE_CASE = 'model.sqout.%d.weight' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/moe' ): SCREAMING_SNAKE_CASE = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/switch_gating/kernel' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.router.classifier.weight' % player SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/softmlp/kernel' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.soft_bypass_mlp.weight' % player SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/wo/kernel' ) or key_name.endswith('/wi/kernel' ): SCREAMING_SNAKE_CASE = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight' % (player, i, nlayer) SCREAMING_SNAKE_CASE = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/mlp' ): SCREAMING_SNAKE_CASE = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/p1/kernel' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.wi.weight' % player SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/p1/bias' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.wi.bias' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/p2/kernel' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.wo.weight' % player SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/p2/bias' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.mlp.wo.bias' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/ln' ): SCREAMING_SNAKE_CASE = int(key_name[8:].split('/' )[0] ) if key_name.endswith('/b' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.norm.bias' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/g' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.feed_forward.norm.weight' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/att' ): SCREAMING_SNAKE_CASE = int(key_name[9:].split('/' )[0] ) if key_name.endswith('/qkv/kernel' ): SCREAMING_SNAKE_CASE = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE = state[:, 0, :, :] SCREAMING_SNAKE_CASE = state[:, 1, :, :] SCREAMING_SNAKE_CASE = state[:, 2, :, :] SCREAMING_SNAKE_CASE = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.self_attn.q_proj.weight' % player SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.self_attn.k_proj.weight' % player SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.self_attn.v_proj.weight' % player SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/o/kernel' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.self_attn.out_proj.weight' % player SCREAMING_SNAKE_CASE = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/an' ): SCREAMING_SNAKE_CASE = int(key_name[8:].split('/' )[0] ) if key_name.endswith('/b' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.norm.bias' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.endswith('/g' ): SCREAMING_SNAKE_CASE = 'model.blocks.%d.self_attn.norm.weight' % player SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif ( key_name.startswith('model/wte' ) or key_name.startswith('model/wpe' ) or key_name.startswith('model/ete' ) ): SCREAMING_SNAKE_CASE = {'wte': 'embed_tokens', 'wpe': 'position_embeddings', 'ete': 'extra_position_embeddings'}[ key_name[-3:] ] SCREAMING_SNAKE_CASE = 'model.%s.weight' % nlayer SCREAMING_SNAKE_CASE = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) if key_name.startswith('model/wte' ): SCREAMING_SNAKE_CASE = 'lm_head.weight' SCREAMING_SNAKE_CASE = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name.startswith('model/wob' ): SCREAMING_SNAKE_CASE = 'final_logits_bias' SCREAMING_SNAKE_CASE = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE = 'model.last_project.weight' SCREAMING_SNAKE_CASE = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE = 'model.last_project.bias' SCREAMING_SNAKE_CASE = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE = torch.tensor(_UpperCamelCase ) torch.save(_UpperCamelCase , args.output ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser( description='''model converter.''', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('''--tf_model_dir''', metavar='''PATH''', type=str, required=True, help='''import model''') parser.add_argument('''--output''', metavar='''PATH''', type=str, required=True, help='''output model''') __UpperCamelCase = parser.parse_args() convert_tf_gptsan_to_pt(args)
359
"""simple docstring""" import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) __UpperCamelCase = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='''relu''') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='''relu''')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='''relu''')) classifier.add(layers.Dense(units=1, activation='''sigmoid''')) # Compiling the CNN classifier.compile( optimizer='''adam''', loss='''binary_crossentropy''', metrics=['''accuracy'''] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') __UpperCamelCase = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) __UpperCamelCase = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) __UpperCamelCase = train_datagen.flow_from_directory( '''dataset/training_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) __UpperCamelCase = test_datagen.flow_from_directory( '''dataset/test_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('''cnn.h5''') # Part 3 - Making new predictions __UpperCamelCase = tf.keras.preprocessing.image.load_img( '''dataset/single_prediction/image.png''', target_size=(64, 64) ) __UpperCamelCase = tf.keras.preprocessing.image.img_to_array(test_image) __UpperCamelCase = np.expand_dims(test_image, axis=0) __UpperCamelCase = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: __UpperCamelCase = '''Normal''' if result[0][0] == 1: __UpperCamelCase = '''Abnormality detected'''
38
0
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _lowerCamelCase : Optional[int] = ( "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) ) _lowerCamelCase : Union[str, Any] = ( ("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"), ) _lowerCamelCase : Dict = ( ("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), ) _lowerCamelCase : Dict = ( ("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), ) _lowerCamelCase : Optional[Any] = ( ("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]), ) _lowerCamelCase : List[Any] = ( ("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), ) _lowerCamelCase : List[str] = ( ("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 ( ) -> Optional[Any]: """simple docstring""" UpperCamelCase , UpperCamelCase = randrange(len(A__ ) ), randrange(len(A__ ) ) UpperCamelCase = ['Loss', 'Tie', 'Win'][(play >= oppo) + (play > oppo)] UpperCamelCase , UpperCamelCase = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __lowerCamelCase ( A__ = 100 ) -> Optional[Any]: """simple docstring""" return (generate_random_hand() for _ in range(A__ )) @pytest.mark.parametrize('hand, expected' , A__ ) def __lowerCamelCase ( A__ , A__ ) -> Any: """simple docstring""" assert PokerHand(A__ )._is_flush() == expected @pytest.mark.parametrize('hand, expected' , A__ ) def __lowerCamelCase ( A__ , A__ ) -> Any: """simple docstring""" assert PokerHand(A__ )._is_straight() == expected @pytest.mark.parametrize('hand, expected, card_values' , A__ ) def __lowerCamelCase ( A__ , A__ , A__ ) -> str: """simple docstring""" UpperCamelCase = 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__ ) -> Dict: """simple docstring""" assert PokerHand(A__ )._is_same_kind() == expected @pytest.mark.parametrize('hand, expected' , A__ ) def __lowerCamelCase ( A__ , A__ ) -> str: """simple docstring""" assert PokerHand(A__ )._hand_type == expected @pytest.mark.parametrize('hand, other, expected' , A__ ) def __lowerCamelCase ( A__ , A__ , A__ ) -> Tuple: """simple docstring""" assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected @pytest.mark.parametrize('hand, other, expected' , generate_random_hands() ) def __lowerCamelCase ( A__ , A__ , A__ ) -> List[str]: """simple docstring""" assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected def __lowerCamelCase ( ) -> str: """simple docstring""" UpperCamelCase = [PokerHand(A__ ) for hand in SORTED_HANDS] UpperCamelCase = poker_hands.copy() shuffle(A__ ) UpperCamelCase = chain(sorted(A__ ) ) for index, hand in enumerate(A__ ): assert hand == poker_hands[index] def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" # Test that five high straights are compared correctly. UpperCamelCase = [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 ( ) -> str: """simple docstring""" # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. UpperCamelCase = PokerHand('2C 4S AS 3D 5C' ) UpperCamelCase = True UpperCamelCase = [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 ( ) -> List[str]: """simple docstring""" # Problem number 54 from Project Euler # Testing from poker_hands.txt file UpperCamelCase = 0 UpperCamelCase = os.path.abspath(os.path.dirname(A__ ) ) UpperCamelCase = os.path.join(A__ , 'poker_hands.txt' ) with open(A__ ) as file_hand: for line in file_hand: UpperCamelCase = line[:14].strip() UpperCamelCase = line[15:].strip() UpperCamelCase , UpperCamelCase = PokerHand(A__ ), PokerHand(A__ ) UpperCamelCase = player.compare_with(A__ ) if output == "Win": answer += 1 assert answer == 376
28
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ : List[Any] = logging.get_logger(__name__) lowerCamelCase__ : List[str] = { 'vocab_file': 'vocab.json', 'tokenizer_config_file': 'tokenizer_config.json', 'merges_file': 'merges.txt', } lowerCamelCase__ : Union[str, Any] = { 'vocab_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json' ), }, 'tokenizer_config_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json' ), }, 'merges_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt' ), }, } lowerCamelCase__ : Optional[Any] = '</w>' lowerCamelCase__ : Union[str, Any] = '@@ ' def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] ) -> Dict: SCREAMING_SNAKE_CASE_ = set() SCREAMING_SNAKE_CASE_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE_ = char return pairs # Speech2Text2 has no max input length lowerCamelCase__ : Any = {'facebook/s2t-wav2vec2-large-en-de': 1_024} class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = ["input_ids", "attention_mask"] def __init__( self : List[str] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any]="<s>" , _lowerCAmelCase : Any="<pad>" , _lowerCAmelCase : List[str]="</s>" , _lowerCAmelCase : int="<unk>" , _lowerCAmelCase : Optional[Any]=False , _lowerCAmelCase : Dict=None , **_lowerCAmelCase : Tuple , ): super().__init__( unk_token=_lowerCAmelCase , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , **_lowerCAmelCase , ) SCREAMING_SNAKE_CASE_ = do_lower_case with open(_lowerCAmelCase , encoding='utf-8' ) as vocab_handle: SCREAMING_SNAKE_CASE_ = json.load(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F"No merges files provided. {self.__class__.__name__} can only be used for decoding." ) SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None else: with open(_lowerCAmelCase , encoding='utf-8' ) as merges_handle: SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n' )[:-1] SCREAMING_SNAKE_CASE_ = [tuple(merge.split()[:2] ) for merge in merges] SCREAMING_SNAKE_CASE_ = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE_ = {} @property def lowerCAmelCase_ ( self : List[str] ): return len(self.decoder ) def lowerCAmelCase_ ( self : Tuple ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : Tuple ): SCREAMING_SNAKE_CASE_ = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE_ = get_pairs(_lowerCAmelCase ) if not pairs: return token while True: SCREAMING_SNAKE_CASE_ = min(_lowerCAmelCase , key=lambda _lowerCAmelCase : self.bpe_ranks.get(_lowerCAmelCase , float('inf' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 0 while i < len(_lowerCAmelCase ): try: SCREAMING_SNAKE_CASE_ = word.index(_lowerCAmelCase , _lowerCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE_ = j if word[i] == first and i < len(_lowerCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE_ = tuple(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = new_word if len(_lowerCAmelCase ) == 1: break else: SCREAMING_SNAKE_CASE_ = get_pairs(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = ' '.join(_lowerCAmelCase ) if word == "\n " + BPE_TOKEN_MERGES: SCREAMING_SNAKE_CASE_ = '\n' + BPE_TOKEN_MERGES if word.endswith(_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = word.replace(_lowerCAmelCase , '' ) SCREAMING_SNAKE_CASE_ = word.replace(' ' , _lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = word return word def lowerCAmelCase_ ( self : Optional[int] , _lowerCAmelCase : Optional[int] ): if self.bpe_ranks is None: raise ValueError( 'This tokenizer was instantiated without a `merges.txt` file, so' ' that it can only be used for decoding, not for encoding.' 'Make sure to provide `merges.txt` file at instantiation to enable ' 'encoding.' ) if self.do_lower_case: SCREAMING_SNAKE_CASE_ = text.lower() SCREAMING_SNAKE_CASE_ = text.split() SCREAMING_SNAKE_CASE_ = [] for token in text: if token: split_tokens.extend(list(self.bpe(_lowerCAmelCase ).split(' ' ) ) ) return split_tokens def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : str ): return self.encoder.get(_lowerCAmelCase , self.encoder.get(self.unk_token ) ) def lowerCAmelCase_ ( self : int , _lowerCAmelCase : int ): SCREAMING_SNAKE_CASE_ = self.decoder.get(_lowerCAmelCase , self.unk_token ) return result def lowerCAmelCase_ ( self : int , _lowerCAmelCase : List[str] ): SCREAMING_SNAKE_CASE_ = ' '.join(_lowerCAmelCase ) # make sure @@ tokens are concatenated SCREAMING_SNAKE_CASE_ = ''.join(string.split(_lowerCAmelCase ) ) return string def lowerCAmelCase_ ( self : int , _lowerCAmelCase : str , _lowerCAmelCase : Optional[str] = None ): if not os.path.isdir(_lowerCAmelCase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ = os.path.join( _lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE_ = os.path.join( _lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_lowerCAmelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowerCAmelCase , ensure_ascii=_lowerCAmelCase ) + '\n' ) SCREAMING_SNAKE_CASE_ = 0 if self.bpe_ranks is None: return (vocab_file,) with open(_lowerCAmelCase , 'w' , encoding='utf-8' ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _lowerCAmelCase : kv[1] ): if index != token_index: logger.warning( F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive." ' Please check that the tokenizer is not corrupted!' ) SCREAMING_SNAKE_CASE_ = token_index writer.write(' '.join(_lowerCAmelCase ) + '\n' ) index += 1 return (vocab_file, merges_file)
225
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ = { '''configuration_rembert''': ['''REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RemBertConfig''', '''RemBertOnnxConfig'''] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['''RemBertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['''RemBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ '''REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RemBertForCausalLM''', '''RemBertForMaskedLM''', '''RemBertForMultipleChoice''', '''RemBertForQuestionAnswering''', '''RemBertForSequenceClassification''', '''RemBertForTokenClassification''', '''RemBertLayer''', '''RemBertModel''', '''RemBertPreTrainedModel''', '''load_tf_weights_in_rembert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ '''TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRemBertForCausalLM''', '''TFRemBertForMaskedLM''', '''TFRemBertForMultipleChoice''', '''TFRemBertForQuestionAnswering''', '''TFRemBertForSequenceClassification''', '''TFRemBertForTokenClassification''', '''TFRemBertLayer''', '''TFRemBertModel''', '''TFRemBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES snake_case_ = logging.get_logger(__name__) snake_case_ = OrderedDict( [ # Base model mapping ('''albert''', '''FlaxAlbertModel'''), ('''bart''', '''FlaxBartModel'''), ('''beit''', '''FlaxBeitModel'''), ('''bert''', '''FlaxBertModel'''), ('''big_bird''', '''FlaxBigBirdModel'''), ('''blenderbot''', '''FlaxBlenderbotModel'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallModel'''), ('''clip''', '''FlaxCLIPModel'''), ('''distilbert''', '''FlaxDistilBertModel'''), ('''electra''', '''FlaxElectraModel'''), ('''gpt-sw3''', '''FlaxGPT2Model'''), ('''gpt2''', '''FlaxGPT2Model'''), ('''gpt_neo''', '''FlaxGPTNeoModel'''), ('''gptj''', '''FlaxGPTJModel'''), ('''longt5''', '''FlaxLongT5Model'''), ('''marian''', '''FlaxMarianModel'''), ('''mbart''', '''FlaxMBartModel'''), ('''mt5''', '''FlaxMT5Model'''), ('''opt''', '''FlaxOPTModel'''), ('''pegasus''', '''FlaxPegasusModel'''), ('''regnet''', '''FlaxRegNetModel'''), ('''resnet''', '''FlaxResNetModel'''), ('''roberta''', '''FlaxRobertaModel'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormModel'''), ('''roformer''', '''FlaxRoFormerModel'''), ('''t5''', '''FlaxT5Model'''), ('''vision-text-dual-encoder''', '''FlaxVisionTextDualEncoderModel'''), ('''vit''', '''FlaxViTModel'''), ('''wav2vec2''', '''FlaxWav2Vec2Model'''), ('''whisper''', '''FlaxWhisperModel'''), ('''xglm''', '''FlaxXGLMModel'''), ('''xlm-roberta''', '''FlaxXLMRobertaModel'''), ] ) snake_case_ = OrderedDict( [ # Model for pre-training mapping ('''albert''', '''FlaxAlbertForPreTraining'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForPreTraining'''), ('''big_bird''', '''FlaxBigBirdForPreTraining'''), ('''electra''', '''FlaxElectraForPreTraining'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ('''wav2vec2''', '''FlaxWav2Vec2ForPreTraining'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) snake_case_ = OrderedDict( [ # Model for Masked LM mapping ('''albert''', '''FlaxAlbertForMaskedLM'''), ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''bert''', '''FlaxBertForMaskedLM'''), ('''big_bird''', '''FlaxBigBirdForMaskedLM'''), ('''distilbert''', '''FlaxDistilBertForMaskedLM'''), ('''electra''', '''FlaxElectraForMaskedLM'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''roberta''', '''FlaxRobertaForMaskedLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMaskedLM'''), ('''roformer''', '''FlaxRoFormerForMaskedLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMaskedLM'''), ] ) snake_case_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('''bart''', '''FlaxBartForConditionalGeneration'''), ('''blenderbot''', '''FlaxBlenderbotForConditionalGeneration'''), ('''blenderbot-small''', '''FlaxBlenderbotSmallForConditionalGeneration'''), ('''encoder-decoder''', '''FlaxEncoderDecoderModel'''), ('''longt5''', '''FlaxLongT5ForConditionalGeneration'''), ('''marian''', '''FlaxMarianMTModel'''), ('''mbart''', '''FlaxMBartForConditionalGeneration'''), ('''mt5''', '''FlaxMT5ForConditionalGeneration'''), ('''pegasus''', '''FlaxPegasusForConditionalGeneration'''), ('''t5''', '''FlaxT5ForConditionalGeneration'''), ] ) snake_case_ = OrderedDict( [ # Model for Image-classsification ('''beit''', '''FlaxBeitForImageClassification'''), ('''regnet''', '''FlaxRegNetForImageClassification'''), ('''resnet''', '''FlaxResNetForImageClassification'''), ('''vit''', '''FlaxViTForImageClassification'''), ] ) snake_case_ = OrderedDict( [ ('''vision-encoder-decoder''', '''FlaxVisionEncoderDecoderModel'''), ] ) snake_case_ = OrderedDict( [ # Model for Causal LM mapping ('''bart''', '''FlaxBartForCausalLM'''), ('''bert''', '''FlaxBertForCausalLM'''), ('''big_bird''', '''FlaxBigBirdForCausalLM'''), ('''electra''', '''FlaxElectraForCausalLM'''), ('''gpt-sw3''', '''FlaxGPT2LMHeadModel'''), ('''gpt2''', '''FlaxGPT2LMHeadModel'''), ('''gpt_neo''', '''FlaxGPTNeoForCausalLM'''), ('''gptj''', '''FlaxGPTJForCausalLM'''), ('''opt''', '''FlaxOPTForCausalLM'''), ('''roberta''', '''FlaxRobertaForCausalLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForCausalLM'''), ('''xglm''', '''FlaxXGLMForCausalLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForCausalLM'''), ] ) snake_case_ = OrderedDict( [ # Model for Sequence Classification mapping ('''albert''', '''FlaxAlbertForSequenceClassification'''), ('''bart''', '''FlaxBartForSequenceClassification'''), ('''bert''', '''FlaxBertForSequenceClassification'''), ('''big_bird''', '''FlaxBigBirdForSequenceClassification'''), ('''distilbert''', '''FlaxDistilBertForSequenceClassification'''), ('''electra''', '''FlaxElectraForSequenceClassification'''), ('''mbart''', '''FlaxMBartForSequenceClassification'''), ('''roberta''', '''FlaxRobertaForSequenceClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForSequenceClassification'''), ('''roformer''', '''FlaxRoFormerForSequenceClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForSequenceClassification'''), ] ) snake_case_ = OrderedDict( [ # Model for Question Answering mapping ('''albert''', '''FlaxAlbertForQuestionAnswering'''), ('''bart''', '''FlaxBartForQuestionAnswering'''), ('''bert''', '''FlaxBertForQuestionAnswering'''), ('''big_bird''', '''FlaxBigBirdForQuestionAnswering'''), ('''distilbert''', '''FlaxDistilBertForQuestionAnswering'''), ('''electra''', '''FlaxElectraForQuestionAnswering'''), ('''mbart''', '''FlaxMBartForQuestionAnswering'''), ('''roberta''', '''FlaxRobertaForQuestionAnswering'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForQuestionAnswering'''), ('''roformer''', '''FlaxRoFormerForQuestionAnswering'''), ('''xlm-roberta''', '''FlaxXLMRobertaForQuestionAnswering'''), ] ) snake_case_ = OrderedDict( [ # Model for Token Classification mapping ('''albert''', '''FlaxAlbertForTokenClassification'''), ('''bert''', '''FlaxBertForTokenClassification'''), ('''big_bird''', '''FlaxBigBirdForTokenClassification'''), ('''distilbert''', '''FlaxDistilBertForTokenClassification'''), ('''electra''', '''FlaxElectraForTokenClassification'''), ('''roberta''', '''FlaxRobertaForTokenClassification'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForTokenClassification'''), ('''roformer''', '''FlaxRoFormerForTokenClassification'''), ('''xlm-roberta''', '''FlaxXLMRobertaForTokenClassification'''), ] ) snake_case_ = OrderedDict( [ # Model for Multiple Choice mapping ('''albert''', '''FlaxAlbertForMultipleChoice'''), ('''bert''', '''FlaxBertForMultipleChoice'''), ('''big_bird''', '''FlaxBigBirdForMultipleChoice'''), ('''distilbert''', '''FlaxDistilBertForMultipleChoice'''), ('''electra''', '''FlaxElectraForMultipleChoice'''), ('''roberta''', '''FlaxRobertaForMultipleChoice'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForMultipleChoice'''), ('''roformer''', '''FlaxRoFormerForMultipleChoice'''), ('''xlm-roberta''', '''FlaxXLMRobertaForMultipleChoice'''), ] ) snake_case_ = OrderedDict( [ ('''bert''', '''FlaxBertForNextSentencePrediction'''), ] ) snake_case_ = OrderedDict( [ ('''speech-encoder-decoder''', '''FlaxSpeechEncoderDecoderModel'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ] ) snake_case_ = OrderedDict( [ ('''whisper''', '''FlaxWhisperForAudioClassification'''), ] ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : str = FLAX_MODEL_MAPPING snake_case_ = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='''pretraining''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='''causal language modeling''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Optional[int] = FLAX_MODEL_FOR_MASKED_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='''masked language modeling''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Optional[int] = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='''sequence-to-sequence language modeling''', checkpoint_for_example='''t5-base''' ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Dict = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='''sequence classification''' ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='''question answering''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='''token classification''' ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : str = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='''multiple choice''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Union[str, Any] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='''next sentence prediction''' ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Union[str, Any] = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='''image classification''' ) class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : Tuple = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='''vision-to-text modeling''') class SCREAMING_SNAKE_CASE__ (_BaseAutoModelClass ): __lowerCamelCase : List[str] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='''sequence-to-sequence speech-to-text modeling''' )
216
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__ : Optional[int] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
207
def a ( lowerCamelCase_ ): '''simple docstring''' lowercase__ = [1] lowercase__ , lowercase__ , lowercase__ = 0, 0, 0 lowercase__ = ugly_nums[ia] * 2 lowercase__ = ugly_nums[ia] * 3 lowercase__ = ugly_nums[ia] * 5 for _ in range(1 , lowerCamelCase_ ): lowercase__ = min(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) ugly_nums.append(lowerCamelCase_ ) if next_num == next_a: ia += 1 lowercase__ = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 lowercase__ = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 lowercase__ = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"{ugly_numbers(2_00) = }")
207
1
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder _snake_case = "base_with_context" def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(weights["token_embedder"]["embedding"] ) ) _lowerCAmelCase : str = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCamelCase ) for lyr_num, lyr in enumerate(model.encoders ): _lowerCAmelCase : List[str] = weights[F"layers_{lyr_num}"] _lowerCAmelCase : Dict = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) _lowerCAmelCase : Optional[Any] = ly_weight["attention"] _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _lowerCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _lowerCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _lowerCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _lowerCAmelCase : int = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(weights["input_proj"]["kernel"].T ) ) _lowerCAmelCase : Union[str, Any] = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCamelCase ) for lyr_num, lyr in enumerate(model.encoders ): _lowerCAmelCase : Any = weights[F"layers_{lyr_num}"] _lowerCAmelCase : List[Any] = ly_weight["attention"] _lowerCAmelCase : str = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _lowerCAmelCase : int = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _lowerCAmelCase : List[str] = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _lowerCAmelCase : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["time_emb_dense0"]["kernel"].T ) ) _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(weights["time_emb_dense1"]["kernel"].T ) ) _lowerCAmelCase : List[str] = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = nn.Parameter( torch.FloatTensor(weights["continuous_inputs_projection"]["kernel"].T ) ) for lyr_num, lyr in enumerate(model.decoders ): _lowerCAmelCase : List[Any] = weights[F"layers_{lyr_num}"] _lowerCAmelCase : str = nn.Parameter( torch.FloatTensor(ly_weight["pre_self_attention_layer_norm"]["scale"] ) ) _lowerCAmelCase : str = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_0"]["DenseGeneral_0"]["kernel"].T ) ) _lowerCAmelCase : Tuple = ly_weight["self_attention"] _lowerCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _lowerCAmelCase : str = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _lowerCAmelCase : int = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _lowerCAmelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _lowerCAmelCase : Dict = ly_weight["MultiHeadDotProductAttention_0"] _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) _lowerCAmelCase : int = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) _lowerCAmelCase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) _lowerCAmelCase : Tuple = nn.Parameter( torch.FloatTensor(ly_weight["pre_cross_attention_layer_norm"]["scale"] ) ) _lowerCAmelCase : Any = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) _lowerCAmelCase : List[str] = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_1"]["DenseGeneral_0"]["kernel"].T ) ) _lowerCAmelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) _lowerCAmelCase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) _lowerCAmelCase : int = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) _lowerCAmelCase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["decoder_norm"]["scale"] ) ) _lowerCAmelCase : Dict = nn.Parameter(torch.FloatTensor(weights["spec_out_dense"]["kernel"].T ) ) return model def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : str = checkpoints.load_tax_checkpoint(args.checkpoint_path ) _lowerCAmelCase : Tuple = jnp.tree_util.tree_map(onp.array , _lowerCamelCase ) _lowerCAmelCase : Dict = [ "from __gin__ import dynamic_registration", "from music_spectrogram_diffusion.models.diffusion import diffusion_utils", "diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0", "diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()", ] _lowerCAmelCase : List[Any] = os.path.join(args.checkpoint_path , ".." , "config.gin" ) _lowerCAmelCase : List[str] = inference.parse_training_gin_file(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : Optional[Any] = inference.InferenceModel(args.checkpoint_path , _lowerCamelCase ) _lowerCAmelCase : Dict = DDPMScheduler(beta_schedule="squaredcos_cap_v2" , variance_type="fixed_large" ) _lowerCAmelCase : Any = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["inputs"] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) _lowerCAmelCase : List[Any] = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["targets_context"] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) _lowerCAmelCase : Optional[Any] = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["targets_context"] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) _lowerCAmelCase : Optional[int] = load_notes_encoder(ta_checkpoint["target"]["token_encoder"] , _lowerCamelCase ) _lowerCAmelCase : Optional[Any] = load_continuous_encoder(ta_checkpoint["target"]["continuous_encoder"] , _lowerCamelCase ) _lowerCAmelCase : List[Any] = load_decoder(ta_checkpoint["target"]["decoder"] , _lowerCamelCase ) _lowerCAmelCase : Optional[int] = OnnxRuntimeModel.from_pretrained("kashif/soundstream_mel_decoder" ) _lowerCAmelCase : str = SpectrogramDiffusionPipeline( notes_encoder=_lowerCamelCase , continuous_encoder=_lowerCamelCase , decoder=_lowerCamelCase , scheduler=_lowerCamelCase , melgan=_lowerCamelCase , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("--output_path", default=None, type=str, required=True, help="Path to the converted model.") parser.add_argument( "--save", default=True, type=bool, required=False, help="Whether to save the converted model or not." ) parser.add_argument( "--checkpoint_path", default=f'''{MODEL}/checkpoint_500000''', type=str, required=False, help="Path to the original jax model checkpoint.", ) _snake_case = parser.parse_args() main(args)
300
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def A ( _lowerCamelCase = 8 ): '''simple docstring''' _lowerCAmelCase : Optional[int] = ascii_letters + digits + punctuation return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' i -= len(_lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = i // 3 _lowerCAmelCase : List[Any] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) _lowerCAmelCase : str = ( chars_incl + random(_lowerCamelCase , quotient + remainder ) + random(_lowerCamelCase , _lowerCamelCase ) + random(_lowerCamelCase , _lowerCamelCase ) ) _lowerCAmelCase : str = list(_lowerCamelCase ) shuffle(_lowerCamelCase ) return "".join(_lowerCamelCase ) # random is a generalised function for letters, characters and numbers def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' pass # Put your code here... def A ( _lowerCamelCase , _lowerCamelCase = 8 ): '''simple docstring''' if len(_lowerCamelCase ) < min_length: # Your Password must be at least 8 characters long return False _lowerCAmelCase : Tuple = any(char in ascii_uppercase for char in password ) _lowerCAmelCase : Tuple = any(char in ascii_lowercase for char in password ) _lowerCAmelCase : Optional[Any] = any(char in digits for char in password ) _lowerCAmelCase : Tuple = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def A ( ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = int(input("Please indicate the max length of your password: " ).strip() ) _lowerCAmelCase : Tuple = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(_lowerCamelCase ) ) print( "Alternative Password generated:" , alternative_password_generator(_lowerCamelCase , _lowerCamelCase ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
300
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : Any = { """configuration_clipseg""": [ """CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPSegConfig""", """CLIPSegTextConfig""", """CLIPSegVisionConfig""", ], """processing_clipseg""": ["""CLIPSegProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ """CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPSegModel""", """CLIPSegPreTrainedModel""", """CLIPSegTextModel""", """CLIPSegVisionModel""", """CLIPSegForImageSegmentation""", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowercase__ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
224
"""simple docstring""" from __future__ import annotations def UpperCamelCase_ ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ) -> bool: """simple docstring""" if len(lowerCAmelCase__ ) == 0: return False lowerCAmelCase_ : Union[str, Any] = len(lowerCAmelCase__ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , lowerCAmelCase__ ) else: return binary_search(a_list[midpoint + 1 :] , lowerCAmelCase__ ) if __name__ == "__main__": lowercase__ : str = input("""Enter numbers separated by comma:\n""").strip() lowercase__ : Optional[int] = [int(item.strip()) for item in user_input.split(""",""")] lowercase__ : Optional[Any] = int(input("""Enter the number to be found in the list:\n""").strip()) lowercase__ : int = """""" if binary_search(sequence, target) else """not """ print(f'{target} was {not_str}found in {sequence}')
224
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = ArgumentParser( description=( '''PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=a__ , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=a__ , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=a__ ) return parser.parse_args() def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = parse_args() # Import training_script as a module. SCREAMING_SNAKE_CASE : Optional[Any] = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) SCREAMING_SNAKE_CASE : Optional[int] = script_fpath.stem SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module(a__ ) # Patch sys.argv SCREAMING_SNAKE_CASE : str = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
359
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 while True: if is_prime(a__ ): yield num num += 1 def UpperCAmelCase_( a__ = 2_000_000 ): """simple docstring""" return sum(takewhile(lambda a__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
19
0
'''simple docstring''' def lowerCAmelCase_ ( _lowerCamelCase: str ): if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) __SCREAMING_SNAKE_CASE : Tuple = sorted(string.lower() ) return len(_lowerCamelCase ) == len(set(_lowerCamelCase ) ) if __name__ == "__main__": UpperCamelCase__ : Any = input('''Enter a string ''').strip() UpperCamelCase__ : str = is_isogram(input_str) print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
112
'''simple docstring''' import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : Any = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase__ : Union[str, Any] = { '''vocab_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase__ : Optional[int] = { '''vocab_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase__ : Optional[Any] = { '''vocab_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase__ : Any = { '''facebook/dpr-ctx_encoder-single-nq-base''': 5_12, '''facebook/dpr-ctx_encoder-multiset-base''': 5_12, } UpperCamelCase__ : Optional[Any] = { '''facebook/dpr-question_encoder-single-nq-base''': 5_12, '''facebook/dpr-question_encoder-multiset-base''': 5_12, } UpperCamelCase__ : Dict = { '''facebook/dpr-reader-single-nq-base''': 5_12, '''facebook/dpr-reader-multiset-base''': 5_12, } UpperCamelCase__ : Optional[int] = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase__ : Optional[Any] = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase__ : Any = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class _UpperCamelCase ( lowerCamelCase__ ): '''simple docstring''' _A : str = VOCAB_FILES_NAMES _A : str = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _A : Any = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _A : Any = DPRContextEncoderTokenizer class _UpperCamelCase ( lowerCamelCase__ ): '''simple docstring''' _A : Dict = VOCAB_FILES_NAMES _A : Any = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _A : Tuple = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : Union[str, Any] = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _A : Dict = DPRQuestionEncoderTokenizer UpperCamelCase__ : str = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase__ : List[Any] = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase__ : Any = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(lowerCamelCase__ ) class _UpperCamelCase : '''simple docstring''' def __call__( self : str , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : str , ): """simple docstring""" if titles is None and texts is None: return super().__call__( lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) elif titles is None or texts is None: __SCREAMING_SNAKE_CASE : List[Any] = titles if texts is None else texts return super().__call__( lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Dict = titles if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else [titles] __SCREAMING_SNAKE_CASE : Tuple = texts if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else [texts] __SCREAMING_SNAKE_CASE : Optional[Any] = len(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Tuple = questions if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else [questions] * n_passages assert len(lowerCAmelCase__ ) == len( lowerCAmelCase__ ), F"There should be as many titles than texts but got {len(lowerCAmelCase__ )} titles and {len(lowerCAmelCase__ )} texts." __SCREAMING_SNAKE_CASE : int = super().__call__(lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ )["""input_ids"""] __SCREAMING_SNAKE_CASE : str = super().__call__(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ )["""input_ids"""] __SCREAMING_SNAKE_CASE : Optional[Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCAmelCase__ , lowerCAmelCase__ ) ] } if return_attention_mask is not False: __SCREAMING_SNAKE_CASE : int = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __SCREAMING_SNAKE_CASE : int = attention_mask return self.pad(lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ ) def UpperCamelCase__ ( self : Union[str, Any] , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 1_6 , lowerCAmelCase__ : int = 6_4 , lowerCAmelCase__ : int = 4 , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = reader_input["""input_ids"""] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = reader_output[:3] __SCREAMING_SNAKE_CASE : Tuple = len(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = sorted(range(lowerCAmelCase__ ) , reverse=lowerCAmelCase__ , key=relevance_logits.__getitem__ ) __SCREAMING_SNAKE_CASE : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __SCREAMING_SNAKE_CASE : Tuple = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __SCREAMING_SNAKE_CASE : Any = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __SCREAMING_SNAKE_CASE : List[Any] = sequence_ids.index(self.pad_token_id ) else: __SCREAMING_SNAKE_CASE : Any = len(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Tuple = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCAmelCase__ , top_spans=lowerCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowerCAmelCase__ , start_index=lowerCAmelCase__ , end_index=lowerCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(lowerCAmelCase__ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def UpperCamelCase__ ( self : str , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = [] for start_index, start_score in enumerate(lowerCAmelCase__ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __SCREAMING_SNAKE_CASE : Optional[Any] = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : x[1] , reverse=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F"Wrong span indices: [{start_index}:{end_index}]" __SCREAMING_SNAKE_CASE : Optional[Any] = end_index - start_index + 1 assert length <= max_answer_length, F"Span is too long: {length} > {max_answer_length}" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(lowerCAmelCase__ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(lowerCamelCase__ ) class _UpperCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' _A : Optional[int] = VOCAB_FILES_NAMES _A : int = READER_PRETRAINED_VOCAB_FILES_MAP _A : str = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : str = READER_PRETRAINED_INIT_CONFIGURATION _A : Dict = ['''input_ids''', '''attention_mask'''] _A : Tuple = DPRReaderTokenizer
112
1
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = VQModel lowercase__ = """sample""" @property def lowercase_ ( self : List[str] , __snake_case : Tuple=(32, 32) ): a : Optional[int] = 4 a : str = 3 a : int = floats_tensor((batch_size, num_channels) + sizes ).to(__snake_case ) return {"sample": image} @property def lowercase_ ( self : Union[str, Any] ): return (3, 32, 32) @property def lowercase_ ( self : Tuple ): return (3, 32, 32) def lowercase_ ( self : Any ): a : int = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } a : Dict = self.dummy_input return init_dict, inputs_dict def lowercase_ ( self : int ): pass def lowercase_ ( self : Optional[Any] ): pass def lowercase_ ( self : Optional[int] ): a , a : Any = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(__snake_case ) a : int = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowercase_ ( self : List[str] ): a : Optional[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' ) model.to(__snake_case ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) a : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) a : int = image.to(__snake_case ) with torch.no_grad(): a : List[str] = model(__snake_case ).sample a : Optional[Any] = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off a : Dict = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(__snake_case , __snake_case , atol=1e-3 ) )
96
'''simple docstring''' import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class a__( tf.keras.optimizers.schedules.LearningRateSchedule ): def __init__( self : Optional[Any] , __snake_case : float , __snake_case : Callable , __snake_case : int , __snake_case : float = 1.0 , __snake_case : str = None , ): super().__init__() a : Dict = initial_learning_rate a : Optional[int] = warmup_steps a : Tuple = power a : str = decay_schedule_fn a : Optional[int] = name def __call__( self : List[Any] , __snake_case : int ): with tf.name_scope(self.name or 'WarmUp' ) as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. a : Optional[int] = tf.cast(__snake_case , tf.floataa ) a : Tuple = tf.cast(self.warmup_steps , tf.floataa ) a : str = global_step_float / warmup_steps_float a : Union[str, Any] = self.initial_learning_rate * tf.math.pow(__snake_case , self.power ) return tf.cond( global_step_float < warmup_steps_float , lambda: warmup_learning_rate , lambda: self.decay_schedule_fn(step - self.warmup_steps ) , name=__snake_case , ) def lowercase_ ( self : Dict ): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } def lowerCamelCase__ ( _A , _A , _A , _A = 0.0 , _A = 0.9 , _A = 0.999 , _A = 1E-8 , _A = None , _A = None , _A = 0.0 , _A = 1.0 , _A = None , ): a : Optional[int] = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=_A , decay_steps=num_train_steps - num_warmup_steps , end_learning_rate=init_lr * min_lr_ratio , power=_A , ) if num_warmup_steps: a : Tuple = WarmUp( initial_learning_rate=_A , decay_schedule_fn=_A , warmup_steps=_A , ) if weight_decay_rate > 0.0: a : List[Any] = AdamWeightDecay( learning_rate=_A , weight_decay_rate=_A , beta_a=_A , beta_a=_A , epsilon=_A , clipnorm=_A , global_clipnorm=_A , exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'] , include_in_weight_decay=_A , ) else: a : Tuple = tf.keras.optimizers.Adam( learning_rate=_A , beta_a=_A , beta_a=_A , epsilon=_A , clipnorm=_A , global_clipnorm=_A , ) # We return the optimizer and the LR scheduler in order to better track the # evolution of the LR independently of the optimizer. return optimizer, lr_schedule class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001 , __snake_case : float = 0.9 , __snake_case : float = 0.999 , __snake_case : float = 1e-7 , __snake_case : bool = False , __snake_case : float = 0.0 , __snake_case : Optional[List[str]] = None , __snake_case : Optional[List[str]] = None , __snake_case : str = "AdamWeightDecay" , **__snake_case : Optional[int] , ): super().__init__(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , **__snake_case ) a : Tuple = weight_decay_rate a : Optional[Any] = include_in_weight_decay a : Any = exclude_from_weight_decay @classmethod def lowercase_ ( cls : Any , __snake_case : Optional[Any] ): a : Any = {'WarmUp': WarmUp} return super(__snake_case , cls ).from_config(__snake_case , custom_objects=__snake_case ) def lowercase_ ( self : str , __snake_case : Optional[int] , __snake_case : Dict , __snake_case : Optional[int] ): super(__snake_case , self )._prepare_local(__snake_case , __snake_case , __snake_case ) a : List[str] = tf.constant( self.weight_decay_rate , name='adam_weight_decay_rate' ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : List[Any] , __snake_case : str ): a : Optional[Any] = self._do_use_weight_decay(var.name ) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['weight_decay_rate'] , use_locking=self._use_locking , ) return tf.no_op() def lowercase_ ( self : List[str] , __snake_case : List[str] , __snake_case : Any=None , **__snake_case : Tuple ): a , a : Dict = list(zip(*__snake_case ) ) return super(__snake_case , self ).apply_gradients(zip(__snake_case , __snake_case ) , name=__snake_case , **__snake_case ) def lowercase_ ( self : List[Any] , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : Optional[int] ): if apply_state is None: return self._decayed_lr_t[var_dtype], {} a : List[Any] = apply_state or {} a : Optional[Any] = apply_state.get((var_device, var_dtype) ) if coefficients is None: a : int = self._fallback_apply_state(__snake_case , __snake_case ) a : Any = coefficients return coefficients["lr_t"], {"apply_state": apply_state} def lowercase_ ( self : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Tuple=None ): a , a : List[Any] = self._get_lr(var.device , var.dtype.base_dtype , __snake_case ) a : List[Any] = self._decay_weights_op(__snake_case , __snake_case , __snake_case ) with tf.control_dependencies([decay] ): return super(__snake_case , self )._resource_apply_dense(__snake_case , __snake_case , **__snake_case ) def lowercase_ ( self : Any , __snake_case : Optional[Any] , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : int=None ): a , a : Tuple = self._get_lr(var.device , var.dtype.base_dtype , __snake_case ) a : int = self._decay_weights_op(__snake_case , __snake_case , __snake_case ) with tf.control_dependencies([decay] ): return super(__snake_case , self )._resource_apply_sparse(__snake_case , __snake_case , __snake_case , **__snake_case ) def lowercase_ ( self : Optional[Any] ): a : Union[str, Any] = super().get_config() config.update({'weight_decay_rate': self.weight_decay_rate} ) return config def lowercase_ ( self : List[str] , __snake_case : Dict ): if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(__snake_case , __snake_case ) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(__snake_case , __snake_case ) is not None: return False return True class a__( lowerCamelCase__ ): def __init__( self : List[str] ): a : List[Any] = [] a : Optional[int] = None @property def lowercase_ ( self : Any ): if self._accum_steps is None: a : List[Any] = tf.Variable( tf.constant(0 , dtype=tf.intaa ) , trainable=__snake_case , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , ) return self._accum_steps.value() @property def lowercase_ ( self : Optional[int] ): if not self._gradients: raise ValueError('The accumulator should be called first to initialize the gradients' ) return [gradient.value() if gradient is not None else gradient for gradient in self._gradients] def __call__( self : List[Any] , __snake_case : Any ): if not self._gradients: a : Union[str, Any] = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(__snake_case ) , trainable=__snake_case , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , ) if gradient is not None else gradient for gradient in gradients ] ) if len(__snake_case ) != len(self._gradients ): raise ValueError(F"""Expected {len(self._gradients )} gradients, but got {len(__snake_case )}""" ) for accum_gradient, gradient in zip(self._gradients , __snake_case ): if accum_gradient is not None and gradient is not None: accum_gradient.assign_add(__snake_case ) self._accum_steps.assign_add(1 ) def lowercase_ ( self : Tuple ): if not self._gradients: return self._accum_steps.assign(0 ) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(__snake_case ) )
96
1
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCAmelCase_ : int = '''bert-base-cased''' UpperCAmelCase_ : Any = '''fp16''' UpperCAmelCase_ : str = '''bf16''' UpperCAmelCase_ : int = [FPaa, BFaa] @require_fsdp @require_cuda class _SCREAMING_SNAKE_CASE ( _a ): def _A ( self : List[Any] ): super().setUp() UpperCamelCase :Tuple = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _A ( self : List[str] ): from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): UpperCamelCase :Union[str, Any] = self.dist_env.copy() UpperCamelCase :List[Any] = F"""{i + 1}""" UpperCamelCase :List[Any] = strategy with mockenv_context(**__lowerCamelCase ): UpperCamelCase :List[str] = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _A ( self : str ): from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): UpperCamelCase :str = self.dist_env.copy() UpperCamelCase :List[Any] = prefetch_policy with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Optional[int] = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _A ( self : Union[str, Any] ): from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): UpperCamelCase :Any = self.dist_env.copy() UpperCamelCase :Tuple = state_dict_type with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Dict = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _A ( self : Tuple ): UpperCamelCase :int = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: UpperCamelCase :Any = self.dist_env.copy() UpperCamelCase :Dict = policy if policy == "TRANSFORMER_BASED_WRAP": UpperCamelCase :Any = """BertLayer""" elif policy == "SIZE_BASED_WRAP": UpperCamelCase :Optional[Any] = """2000""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :int = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) UpperCamelCase :List[Any] = self.dist_env.copy() UpperCamelCase :Optional[int] = """TRANSFORMER_BASED_WRAP""" UpperCamelCase :int = """T5Layer""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Any = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) UpperCamelCase :List[str] = self.dist_env.copy() UpperCamelCase :str = """SIZE_BASED_WRAP""" UpperCamelCase :int = """0""" with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Optional[Any] = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _A ( self : str ): from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: UpperCamelCase :List[Any] = self.dist_env.copy() UpperCamelCase :Union[str, Any] = mp_dtype with mockenv_context(**__lowerCamelCase ): UpperCamelCase :Dict = Accelerator() if mp_dtype == "fp16": UpperCamelCase :int = torch.floataa elif mp_dtype == "bf16": UpperCamelCase :Union[str, Any] = torch.bfloataa UpperCamelCase :Dict = MixedPrecision(param_dtype=__lowerCamelCase , reduce_dtype=__lowerCamelCase , buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def _A ( self : Dict ): from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: UpperCamelCase :Union[str, Any] = self.dist_env.copy() UpperCamelCase :Union[str, Any] = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): UpperCamelCase :int = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class _SCREAMING_SNAKE_CASE ( _a ): def _A ( self : List[Any] ): super().setUp() UpperCamelCase :Optional[int] = 0.82 UpperCamelCase :Any = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] UpperCamelCase :List[Any] = { """multi_gpu_fp16""": 3_200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2_000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1_900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } UpperCamelCase :Optional[int] = 160 UpperCamelCase :Union[str, Any] = 160 UpperCamelCase :Tuple = inspect.getfile(accelerate.test_utils ) UpperCamelCase :str = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _A ( self : Optional[Any] ): UpperCamelCase :Optional[int] = os.path.join(self.test_scripts_folder , """test_performance.py""" ) UpperCamelCase :Any = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: UpperCamelCase :Optional[Any] = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) def _A ( self : int ): UpperCamelCase :Dict = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) UpperCamelCase :List[str] = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__lowerCamelCase ): UpperCamelCase :List[str] = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue UpperCamelCase :Union[str, Any] = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: UpperCamelCase :Dict = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) UpperCamelCase :Optional[Any] = cmd_config[:-1] UpperCamelCase :int = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) def _A ( self : Optional[Any] ): UpperCamelCase :List[Any] = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) UpperCamelCase :Union[str, Any] = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): UpperCamelCase :List[str] = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() )
38
# 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. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase_ : Any = '''Create a default config file for Accelerate with only a few flags set.''' def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int]="no" , __magic_name__ : str = default_json_config_file , __magic_name__ : bool = False ) -> str: """simple docstring""" UpperCamelCase :Any = Path(__magic_name__ ) path.parent.mkdir(parents=__magic_name__ , exist_ok=__magic_name__ ) if path.exists(): print( f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False UpperCamelCase :Dict = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) UpperCamelCase :Optional[Any] = { """compute_environment""": """LOCAL_MACHINE""", """mixed_precision""": mixed_precision, } if torch.cuda.is_available(): UpperCamelCase :Union[str, Any] = torch.cuda.device_count() UpperCamelCase :List[Any] = num_gpus UpperCamelCase :Dict = False if num_gpus > 1: UpperCamelCase :Any = """MULTI_GPU""" else: UpperCamelCase :Any = """NO""" elif is_xpu_available() and use_xpu: UpperCamelCase :Optional[Any] = torch.xpu.device_count() UpperCamelCase :Optional[int] = num_xpus UpperCamelCase :int = False if num_xpus > 1: UpperCamelCase :Union[str, Any] = """MULTI_XPU""" else: UpperCamelCase :Union[str, Any] = """NO""" elif is_npu_available(): UpperCamelCase :List[Any] = torch.npu.device_count() UpperCamelCase :Optional[Any] = num_npus UpperCamelCase :Tuple = False if num_npus > 1: UpperCamelCase :Optional[Any] = """MULTI_NPU""" else: UpperCamelCase :List[Any] = """NO""" else: UpperCamelCase :Any = 0 UpperCamelCase :Optional[Any] = True UpperCamelCase :Optional[Any] = 1 UpperCamelCase :List[str] = """NO""" UpperCamelCase :int = ClusterConfig(**__magic_name__ ) config.to_json_file(__magic_name__ ) return path def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase :Dict = parser.add_parser("""default""" , parents=__magic_name__ , help=__magic_name__ , formatter_class=__magic_name__ ) parser.add_argument( """--config_file""" , default=__magic_name__ , 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'.""" ) , dest="""save_location""" , ) parser.add_argument( """--mixed_precision""" , choices=["""no""", """fp16""", """bf16"""] , type=__magic_name__ , help="""Whether or not to use mixed precision training. """ """Choose between FP16 and BF16 (bfloat16) training. """ """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.""" , default="""no""" , ) parser.set_defaults(func=__magic_name__ ) return parser def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase :Optional[Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"""accelerate configuration saved at {config_file}""" )
38
1
snake_case : str = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", "\"": ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on snake_case : Union[str, Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def lowerCAmelCase_ ( _snake_case : str ) -> str: '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def lowerCAmelCase_ ( _snake_case : str ) -> str: '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' __magic_name__ : Union[str, Any] = "Morse code here!" print(_snake_case ) __magic_name__ : List[Any] = encrypt(_snake_case ) print(_snake_case ) __magic_name__ : Union[str, Any] = decrypt(_snake_case ) print(_snake_case ) if __name__ == "__main__": main()
41
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() snake_case : Union[str, Any] = logging.get_logger(__name__) snake_case : Optional[int] = ["model.decoder.embed_positions.weights"] def lowerCAmelCase_ ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' if "emb" in name: __magic_name__ : Optional[Any] = name.replace("emb" , "model.decoder.embed_tokens" ) if "transformer" in name: __magic_name__ : List[str] = name.replace("transformer" , "model.decoder" ) if "cross_attention" in name: __magic_name__ : Dict = name.replace("cross_attention" , "encoder_attn" ) if "linear1" in name: __magic_name__ : Optional[Any] = name.replace("linear1" , "fc1" ) if "linear2" in name: __magic_name__ : List[str] = name.replace("linear2" , "fc2" ) if "norm1" in name: __magic_name__ : Optional[int] = name.replace("norm1" , "self_attn_layer_norm" ) if "norm_cross" in name: __magic_name__ : Union[str, Any] = name.replace("norm_cross" , "encoder_attn_layer_norm" ) if "norm2" in name: __magic_name__ : Any = name.replace("norm2" , "final_layer_norm" ) if "out_norm" in name: __magic_name__ : Union[str, Any] = name.replace("out_norm" , "model.decoder.layer_norm" ) if "linears" in name: __magic_name__ : Optional[Any] = name.replace("linears" , "lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: __magic_name__ : Any = name.replace("condition_provider.conditioners.description.output_proj" , "enc_to_dec_proj" ) return name def lowerCAmelCase_ ( _snake_case : OrderedDict , _snake_case : int ) -> Tuple[Dict, Dict]: '''simple docstring''' __magic_name__ : int = list(state_dict.keys() ) __magic_name__ : Dict = {} for key in keys: __magic_name__ : Any = state_dict.pop(_snake_case ) __magic_name__ : Optional[Any] = rename_keys(_snake_case ) if "in_proj_weight" in key: # split fused qkv proj __magic_name__ : Optional[int] = val[:hidden_size, :] __magic_name__ : List[str] = val[hidden_size : 2 * hidden_size, :] __magic_name__ : List[str] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: __magic_name__ : int = val else: __magic_name__ : str = val return state_dict, enc_dec_proj_state_dict def lowerCAmelCase_ ( _snake_case : str ) -> MusicgenDecoderConfig: '''simple docstring''' if checkpoint == "small": # default config values __magic_name__ : Tuple = 1024 __magic_name__ : List[str] = 24 __magic_name__ : str = 16 elif checkpoint == "medium": __magic_name__ : Optional[int] = 1536 __magic_name__ : Dict = 48 __magic_name__ : List[Any] = 24 elif checkpoint == "large": __magic_name__ : Any = 2048 __magic_name__ : int = 48 __magic_name__ : str = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) __magic_name__ : str = MusicgenDecoderConfig( hidden_size=_snake_case , ffn_dim=hidden_size * 4 , num_hidden_layers=_snake_case , num_attention_heads=_snake_case , ) return config @torch.no_grad() def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : Union[str, Any]=None , _snake_case : List[str]=None , _snake_case : Optional[Any]="cpu" ) -> List[str]: '''simple docstring''' __magic_name__ : Dict = MusicGen.get_pretrained(_snake_case , device=_snake_case ) __magic_name__ : Any = decoder_config_from_checkpoint(_snake_case ) __magic_name__ : Any = fairseq_model.lm.state_dict() __magic_name__ , __magic_name__ : Optional[Any] = rename_state_dict( _snake_case , hidden_size=decoder_config.hidden_size ) __magic_name__ : str = TaEncoderModel.from_pretrained("t5-base" ) __magic_name__ : Any = EncodecModel.from_pretrained("facebook/encodec_32khz" ) __magic_name__ : int = MusicgenForCausalLM(_snake_case ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection __magic_name__ , __magic_name__ : List[str] = decoder.load_state_dict(_snake_case , strict=_snake_case ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_snake_case ) if len(_snake_case ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(_snake_case ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model __magic_name__ : Optional[Any] = MusicgenForConditionalGeneration(text_encoder=_snake_case , audio_encoder=_snake_case , decoder=_snake_case ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_snake_case ) # check we can do a forward pass __magic_name__ : Optional[Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) __magic_name__ : List[Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): __magic_name__ : Dict = model(input_ids=_snake_case , decoder_input_ids=_snake_case ).logits if logits.shape != (8, 1, 2048): raise ValueError("Incorrect shape for logits" ) # now construct the processor __magic_name__ : Optional[Any] = AutoTokenizer.from_pretrained("t5-base" ) __magic_name__ : List[str] = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" , padding_side="left" ) __magic_name__ : Union[str, Any] = MusicgenProcessor(feature_extractor=_snake_case , tokenizer=_snake_case ) # set the appropriate bos/pad token ids __magic_name__ : List[str] = 2048 __magic_name__ : List[str] = 2048 # set other default generation config params __magic_name__ : Union[str, Any] = int(30 * audio_encoder.config.frame_rate ) __magic_name__ : Optional[Any] = True __magic_name__ : Dict = 3.0 if pytorch_dump_folder is not None: Path(_snake_case ).mkdir(exist_ok=_snake_case ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(_snake_case ) processor.save_pretrained(_snake_case ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(_snake_case ) processor.push_to_hub(_snake_case ) if __name__ == "__main__": snake_case : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) snake_case : Optional[Any] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
41
1
from manim import * class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def a (self : List[str] ): """simple docstring""" __snake_case = Rectangle(height=0.5 , width=0.5 ) __snake_case = Rectangle(height=0.2_5 , width=0.2_5 ) __snake_case = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) __snake_case = [mem.copy() for i in range(6 )] __snake_case = [mem.copy() for i in range(6 )] __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) __snake_case = Text('''CPU''' , font_size=24 ) __snake_case = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a__ ) __snake_case = [mem.copy() for i in range(4 )] __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = Text('''GPU''' , font_size=24 ) __snake_case = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) gpu.move_to([-1, -1, 0] ) self.add(a__ ) __snake_case = [mem.copy() for i in range(6 )] __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = Text('''Model''' , font_size=24 ) __snake_case = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) model.move_to([3, -1.0, 0] ) self.add(a__ ) __snake_case = [] __snake_case = [] __snake_case = [] for i, rect in enumerate(a__ ): rect.set_stroke(a__ ) __snake_case = Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(a__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=a__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=a__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=a__ , buff=0.0 ) self.add(a__ ) model_cpu_arr.append(a__ ) self.add(*a__ , *a__ , *a__ ) __snake_case = [mem.copy() for i in range(6 )] __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = Text('''Loaded Checkpoint''' , font_size=24 ) __snake_case = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(a__ ) __snake_case = [] __snake_case = [] for i, rect in enumerate(a__ ): __snake_case = fill.copy().set_fill(a__ , opacity=0.7 ) target.move_to(a__ ) ckpt_arr.append(a__ ) __snake_case = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(a__ ) self.add(*a__ , *a__ ) __snake_case = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __snake_case = 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(a__ , a__ ) __snake_case = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(a__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(a__ ) __snake_case = MarkupText( f"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) __snake_case = [meta_mem.copy() for i in range(6 )] __snake_case = [meta_mem.copy() for i in range(6 )] __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = VGroup(*a__ ).arrange(a__ , buff=0 ) __snake_case = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) __snake_case = Text('''Disk''' , font_size=24 ) __snake_case = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) disk.move_to([-4.0, -1.2_5, 0] ) self.play(Write(a__ , run_time=3 ) , Write(a__ , run_time=1 ) , Create(a__ , run_time=1 ) ) __snake_case = [] for i, rect in enumerate(a__ ): __snake_case = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(a__ , run_time=1.5 ) ) self.play(*a__ ) self.play(FadeOut(a__ ) ) __snake_case = MarkupText(f"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(a__ , run_time=3 ) ) self.play( FadeOut(a__ , a__ , *a__ , *a__ ) , ) self.wait()
24
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __snake_case = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def _A ( _lowercase = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __UpperCamelCase = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): __UpperCamelCase = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() __UpperCamelCase = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
310
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ) -> Any: '''simple docstring''' A: Any = mock.Mock() A: List[Any] = 5_00 A: Optional[int] = {} A: Dict = HTTPError A: Dict = {} # Download this model to make sure it's in the cache. A: str = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: A: str = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _snake_case ( self : Optional[Any] ) -> List[str]: '''simple docstring''' A: Tuple = mock.Mock() A: List[str] = 5_00 A: List[str] = {} A: List[str] = HTTPError A: List[str] = {} # Download this model to make sure it's in the cache. A: Tuple = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: A: Optional[int] = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self : Optional[Any] ) -> Any: '''simple docstring''' try: A: Union[str, Any] = tempfile.mktemp() with open(SCREAMING_SNAKE_CASE_ , '''wb''' ) as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , SCREAMING_SNAKE_CASE_ ) A: str = AlbertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) finally: os.remove(SCREAMING_SNAKE_CASE_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('''tokenizer.json''' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('''tokenizer.json''' , '''wb''' ) as f: http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json''' , SCREAMING_SNAKE_CASE_ ) A: Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 10_00 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''' ) def _snake_case ( self : Tuple ) -> Tuple: '''simple docstring''' A: Any = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def _snake_case ( cls : Any ) -> str: '''simple docstring''' A: str = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def _snake_case ( cls : List[Any] ) -> List[str]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-tokenizer''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-tokenizer-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-tokenizer''' ) except HTTPError: pass def _snake_case ( self : Optional[int] ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A: int = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: int = BertTokenizer(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token ) A: List[str] = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ , repo_id='''test-tokenizer''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: Union[str, Any] = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A: Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: List[str] = BertTokenizer(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token ) A: str = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: List[str] = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _snake_case ( self : Union[str, Any] ) -> Any: '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A: Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: Union[str, Any] = CustomTokenizer(SCREAMING_SNAKE_CASE_ ) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) A: List[str] = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A: Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: Optional[int] = BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) A: Dict = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''' ) A: int = AutoTokenizer.from_pretrained( f"""{USER}/test-dynamic-tokenizer""" , use_fast=SCREAMING_SNAKE_CASE_ , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Any ) -> str: '''simple docstring''' A: Tuple = Trie() trie.add('''Hello 友達''' ) self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) trie.add('''Hello''' ) trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS] This is a extra_id_100'''] ) trie.add('''[CLS]''' ) trie.add('''extra_id_1''' ) trie.add('''extra_id_100''' ) self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS]''', ''' This is a ''', '''extra_id_100'''] ) def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' A: Optional[Any] = Trie() trie.add('''A''' ) self.assertEqual(trie.split('''ABC''' ) , ['''A''', '''BC'''] ) self.assertEqual(trie.split('''BCA''' ) , ['''BC''', '''A'''] ) def _snake_case ( self : Dict ) -> Optional[Any]: '''simple docstring''' A: Any = Trie() trie.add('''TOKEN]''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def _snake_case ( self : List[Any] ) -> int: '''simple docstring''' A: Optional[int] = Trie() trie.add('''A''' ) trie.add('''P''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A: Tuple = Trie() trie.add('''AB''' ) trie.add('''B''' ) trie.add('''C''' ) self.assertEqual(trie.split('''ABC''' ) , ['''AB''', '''C'''] ) def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: Optional[int] = Trie() trie.add('''ABC''' ) trie.add('''B''' ) trie.add('''CD''' ) self.assertEqual(trie.split('''ABCD''' ) , ['''ABC''', '''D'''] ) def _snake_case ( self : Any ) -> Any: '''simple docstring''' A: Union[str, Any] = Trie() A: List[str] = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , ['''AB''', '''C'''] )
359
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase = 4 ) -> list[list[int]]: A: Tuple = abs(__lowercase ) or 4 return [[1 + x + y * row_size for x in range(__lowercase )] for y in range(__lowercase )] def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(transpose(__lowercase ) ) # OR.. transpose(reverse_column(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(reverse_column(__lowercase ) ) # OR.. reverse_column(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_column(transpose(__lowercase ) ) # OR.. transpose(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Union[str, Any] = [list(__lowercase ) for x in zip(*__lowercase )] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[int] = matrix[::-1] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[Any] = [x[::-1] for x in matrix] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> None: for i in matrix: print(*__lowercase ) if __name__ == "__main__": UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
334
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 : List[Any] = logging.get_logger(__name__) def lowerCamelCase__ ( ): # Get the sagemaker specific mp parameters from smp_options variable. __UpperCAmelCase : Optional[int] = os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __UpperCAmelCase : Optional[int] = json.loads(__lowerCamelCase ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __UpperCAmelCase : List[str] = os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __UpperCAmelCase : Optional[int] = json.loads(__lowerCamelCase ) if not mpi_options.get("""sagemaker_mpi_enabled""" , __lowerCamelCase ): 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 a ( lowercase__ ): """simple docstring""" a : str = field( default='' , metadata={'help': 'Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'} , ) def UpperCAmelCase ( self : List[Any] ) -> List[str]: super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , __lowercase , ) @cached_property def UpperCAmelCase ( self : Tuple ) -> "torch.device": 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 : List[str] = torch.device("""cpu""" ) __UpperCAmelCase : Tuple = 0 elif is_sagemaker_model_parallel_available(): __UpperCAmelCase : List[Any] = smp.local_rank() __UpperCAmelCase : Tuple = torch.device("""cuda""" , __lowercase ) __UpperCAmelCase : Any = 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 : Dict = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) __UpperCAmelCase : Optional[int] = torch.device("""cuda""" , self.local_rank ) __UpperCAmelCase : Tuple = 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 : 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 : Union[str, 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[int] = torch.device("""cuda""" , self.local_rank ) __UpperCAmelCase : str = 1 if device.type == "cuda": torch.cuda.set_device(__lowercase ) return device @property def UpperCAmelCase ( self : List[str] ) -> List[str]: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase ( self : str ) -> int: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase ( self : str ) -> List[Any]: return False
114
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowercase__ ) class a ( lowercase__ ): """simple docstring""" a : str = field(default='automatic-speech-recognition' , metadata={'include_in_asdict_even_if_is_default': True} ) a : ClassVar[Features] = Features({'audio': Audio()} ) a : ClassVar[Features] = Features({'transcription': Value('string' )} ) a : str = "audio" a : str = "transcription" def UpperCAmelCase ( self : Optional[Any] , __lowercase : Optional[int] ) -> str: if self.audio_column not in features: raise ValueError(f"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowercase ): raise ValueError(f"""Column {self.audio_column} is not an Audio type.""" ) __UpperCAmelCase : int = copy.deepcopy(self ) __UpperCAmelCase : str = self.input_schema.copy() __UpperCAmelCase : List[str] = features[self.audio_column] __UpperCAmelCase : Optional[Any] = input_schema return task_template @property def UpperCAmelCase ( self : Union[str, Any] ) -> Dict[str, str]: return {self.audio_column: "audio", self.transcription_column: "transcription"}
114
1
from __future__ import annotations def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> list[str]: '''simple docstring''' if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) SCREAMING_SNAKE_CASE__ = number_of_bytes // partitions SCREAMING_SNAKE_CASE__ = [] for i in range(UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = i * bytes_per_partition + 1 SCREAMING_SNAKE_CASE__ = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F'{start_bytes}-{end_bytes}' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
169
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _lowercase ( UpperCamelCase_ ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE__ = int(number**0.5 ) return number == sq * sq def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> tuple[int, int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den SCREAMING_SNAKE_CASE__ = x_den * y_den * z_den SCREAMING_SNAKE_CASE__ = gcd(UpperCamelCase_ , UpperCamelCase_ ) top //= hcf bottom //= hcf return top, bottom def _lowercase ( UpperCamelCase_ = 35 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ = set() SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = Fraction(0 ) SCREAMING_SNAKE_CASE__ = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 SCREAMING_SNAKE_CASE__ = x_num * y_den + x_den * y_num SCREAMING_SNAKE_CASE__ = x_den * y_den SCREAMING_SNAKE_CASE__ = gcd(UpperCamelCase_ , UpperCamelCase_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE__ = add_three( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) unique_s.add(UpperCamelCase_ ) # n=2 SCREAMING_SNAKE_CASE__ = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) SCREAMING_SNAKE_CASE__ = x_den * x_den * y_den * y_den if is_sq(UpperCamelCase_ ) and is_sq(UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = int(sqrt(UpperCamelCase_ ) ) SCREAMING_SNAKE_CASE__ = int(sqrt(UpperCamelCase_ ) ) SCREAMING_SNAKE_CASE__ = gcd(UpperCamelCase_ , UpperCamelCase_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE__ = add_three( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) unique_s.add(UpperCamelCase_ ) # n=-1 SCREAMING_SNAKE_CASE__ = x_num * y_num SCREAMING_SNAKE_CASE__ = x_den * y_num + x_num * y_den SCREAMING_SNAKE_CASE__ = gcd(UpperCamelCase_ , UpperCamelCase_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE__ = add_three( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) unique_s.add(UpperCamelCase_ ) # n=2 SCREAMING_SNAKE_CASE__ = x_num * x_num * y_num * y_num SCREAMING_SNAKE_CASE__ = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(UpperCamelCase_ ) and is_sq(UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = int(sqrt(UpperCamelCase_ ) ) SCREAMING_SNAKE_CASE__ = int(sqrt(UpperCamelCase_ ) ) SCREAMING_SNAKE_CASE__ = gcd(UpperCamelCase_ , UpperCamelCase_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE__ = add_three( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) unique_s.add(UpperCamelCase_ ) for num, den in unique_s: total += Fraction(UpperCamelCase_ , UpperCamelCase_ ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
169
1
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Dict , *__lowercase : Union[str, Any] , **__lowercase : Any ): '''simple docstring''' warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , __lowercase , ) super().__init__(*__lowercase , **__lowercase )
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
import argparse import hashlib # hashlib is only used inside the Test class import struct class __SCREAMING_SNAKE_CASE : def __init__( self , SCREAMING_SNAKE_CASE__ ): lowercase : int = data lowercase : Optional[int] = [0x6745_2301, 0xEFCD_AB89, 0x98BA_DCFE, 0x1032_5476, 0xC3D2_E1F0] @staticmethod def __lowerCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return ((n << b) | (n >> (32 - b))) & 0xFFFF_FFFF def __lowerCamelCase ( self ): lowercase : List[Any] = B'''\x80''' + B'''\x00''' * (63 - (len(self.data ) + 8) % 64) lowercase : Dict = self.data + padding + struct.pack('''>Q''' , 8 * len(self.data ) ) return padded_data def __lowerCamelCase ( self ): return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : List[str] = list(struct.unpack('''>16L''' , SCREAMING_SNAKE_CASE__ ) ) + [0] * 64 for i in range(16 , 80 ): lowercase : str = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def __lowerCamelCase ( self ): lowercase : Tuple = self.padding() lowercase : Tuple = self.split_blocks() for block in self.blocks: lowercase : str = self.expand_block(SCREAMING_SNAKE_CASE__ ) lowercase : Optional[int] = self.h for i in range(0 , 80 ): if 0 <= i < 20: lowercase : List[Any] = (b & c) | ((~b) & d) lowercase : Optional[int] = 0x5A82_7999 elif 20 <= i < 40: lowercase : Optional[int] = b ^ c ^ d lowercase : str = 0x6ED9_EBA1 elif 40 <= i < 60: lowercase : Optional[int] = (b & c) | (b & d) | (c & d) lowercase : Dict = 0x8F1B_BCDC elif 60 <= i < 80: lowercase : Tuple = b ^ c ^ d lowercase : Any = 0xCA62_C1D6 lowercase : Dict = ( self.rotate(SCREAMING_SNAKE_CASE__ , 5 ) + f + e + k + expanded_block[i] & 0xFFFF_FFFF, a, self.rotate(SCREAMING_SNAKE_CASE__ , 30 ), c, d, ) lowercase : int = ( self.h[0] + a & 0xFFFF_FFFF, self.h[1] + b & 0xFFFF_FFFF, self.h[2] + c & 0xFFFF_FFFF, self.h[3] + d & 0xFFFF_FFFF, self.h[4] + e & 0xFFFF_FFFF, ) return ("{:08x}" * 5).format(*self.h ) def __lowercase ( ) ->str: """simple docstring""" lowercase : Union[str, Any] = B'''Test String''' assert SHAaHash(_UpperCamelCase ).final_hash() == hashlib.shaa(_UpperCamelCase ).hexdigest() # noqa: S324 def __lowercase ( ) ->List[Any]: """simple docstring""" lowercase : List[str] = argparse.ArgumentParser(description='''Process some strings or files''' ) parser.add_argument( '''--string''', dest='''input_string''', default='''Hello World!! Welcome to Cryptography''', help='''Hash the string''', ) parser.add_argument('''--file''', dest='''input_file''', help='''Hash contents of a file''' ) lowercase : Union[str, Any] = parser.parse_args() lowercase : int = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file, '''rb''' ) as f: lowercase : int = f.read() else: lowercase : Optional[Any] = bytes(_UpperCamelCase, '''utf-8''' ) print(SHAaHash(_UpperCamelCase ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
371
from math import pi, sqrt, tan def __lowercase ( _UpperCamelCase ) ->float: """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def __lowercase ( _UpperCamelCase ) ->float: """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def __lowercase ( _UpperCamelCase ) ->float: """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) lowercase : str = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(_UpperCamelCase, 2 ) * torus_radius * tube_radius def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def __lowercase ( _UpperCamelCase ) ->float: """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) lowercase : List[Any] = (sidea + sidea + sidea) / 2 lowercase : Union[str, Any] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def __lowercase ( _UpperCamelCase ) ->float: """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float: """simple docstring""" if not isinstance(_UpperCamelCase, _UpperCamelCase ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F'''Rectangle: {area_rectangle(10, 20) = }''') print(F'''Square: {area_square(10) = }''') print(F'''Triangle: {area_triangle(10, 10) = }''') print(F'''Triangle: {area_triangle_three_sides(5, 12, 13) = }''') print(F'''Parallelogram: {area_parallelogram(10, 20) = }''') print(F'''Rhombus: {area_rhombus(10, 20) = }''') print(F'''Trapezium: {area_trapezium(10, 20, 30) = }''') print(F'''Circle: {area_circle(20) = }''') print(F'''Ellipse: {area_ellipse(10, 20) = }''') print('''\nSurface Areas of various geometric shapes: \n''') print(F'''Cube: {surface_area_cube(20) = }''') print(F'''Cuboid: {surface_area_cuboid(10, 20, 30) = }''') print(F'''Sphere: {surface_area_sphere(20) = }''') print(F'''Hemisphere: {surface_area_hemisphere(20) = }''') print(F'''Cone: {surface_area_cone(10, 20) = }''') print(F'''Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }''') print(F'''Cylinder: {surface_area_cylinder(10, 20) = }''') print(F'''Torus: {surface_area_torus(20, 10) = }''') print(F'''Equilateral Triangle: {area_reg_polygon(3, 10) = }''') print(F'''Square: {area_reg_polygon(4, 10) = }''') print(F'''Reqular Pentagon: {area_reg_polygon(5, 10) = }''')
173
0
from torch import nn class A_ ( nn.Module ): '''simple docstring''' def __init__(self , lowercase__ , lowercase__ ) -> List[str]: super().__init__() __UpperCAmelCase = class_size __UpperCAmelCase = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) __UpperCAmelCase = nn.Linear(lowercase__ , lowercase__ ) def lowerCAmelCase_ (self , lowercase__ ) -> List[str]: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) __UpperCAmelCase = self.mlp(lowercase__ ) return logits
333
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( _a , unittest.TestCase ): '''simple docstring''' a__ = LongformerTokenizer a__ = True a__ = LongformerTokenizerFast a__ = True def lowerCAmelCase_ (self ) -> Any: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCAmelCase = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] __UpperCAmelCase = dict(zip(lowercase__ , range(len(lowercase__ ) ) ) ) __UpperCAmelCase = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] __UpperCAmelCase = {'''unk_token''': '''<unk>'''} __UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowercase__ ) ) def lowerCAmelCase_ (self , **lowercase__ ) -> int: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase__ ) def lowerCAmelCase_ (self , **lowercase__ ) -> Tuple: kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowercase__ ) def lowerCAmelCase_ (self , lowercase__ ) -> Dict: __UpperCAmelCase = '''lower newer''' __UpperCAmelCase = '''lower newer''' return input_text, output_text def lowerCAmelCase_ (self ) -> Optional[Any]: __UpperCAmelCase = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCAmelCase = '''lower newer''' __UpperCAmelCase = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] __UpperCAmelCase = tokenizer.tokenize(lowercase__ ) # , add_prefix_space=True) self.assertListEqual(lowercase__ , lowercase__ ) __UpperCAmelCase = tokens + [tokenizer.unk_token] __UpperCAmelCase = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) , lowercase__ ) def lowerCAmelCase_ (self ) -> int: __UpperCAmelCase = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' , add_special_tokens=lowercase__ ) , [0, 31_414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' , add_special_tokens=lowercase__ ) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , ) @slow def lowerCAmelCase_ (self ) -> int: __UpperCAmelCase = self.tokenizer_class.from_pretrained('''allenai/longformer-base-4096''' ) __UpperCAmelCase = tokenizer.encode('''sequence builders''' , add_special_tokens=lowercase__ ) __UpperCAmelCase = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowercase__ ) __UpperCAmelCase = tokenizer.encode( '''sequence builders''' , add_special_tokens=lowercase__ , add_prefix_space=lowercase__ ) __UpperCAmelCase = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=lowercase__ , add_prefix_space=lowercase__ ) __UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowercase__ ) __UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowercase__ , lowercase__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def lowerCAmelCase_ (self ) -> Any: __UpperCAmelCase = self.get_tokenizer() __UpperCAmelCase = '''Encode this sequence.''' __UpperCAmelCase = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments __UpperCAmelCase = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ , add_prefix_space=lowercase__ ) __UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(lowercase__ , lowercase__ ) __UpperCAmelCase = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ , add_prefix_space=lowercase__ ) __UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(lowercase__ , lowercase__ ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) __UpperCAmelCase = tokenizer.encode(lowercase__ , add_special_tokens=lowercase__ ) __UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(lowercase__ , lowercase__ ) # Testing spaces after special tokens __UpperCAmelCase = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ )} ) # mask token has a left space __UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowercase__ ) __UpperCAmelCase = '''Encode <mask> sequence''' __UpperCAmelCase = '''Encode <mask>sequence''' __UpperCAmelCase = tokenizer.encode(lowercase__ ) __UpperCAmelCase = encoded.index(lowercase__ ) __UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(lowercase__ , lowercase__ ) __UpperCAmelCase = tokenizer.encode(lowercase__ ) __UpperCAmelCase = encoded.index(lowercase__ ) __UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(lowercase__ , lowercase__ ) def lowerCAmelCase_ (self ) -> Tuple: pass def lowerCAmelCase_ (self ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) __UpperCAmelCase = self.tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) __UpperCAmelCase = '''A, <mask> AllenNLP sentence.''' __UpperCAmelCase = tokenizer_r.encode_plus(lowercase__ , add_special_tokens=lowercase__ , return_token_type_ids=lowercase__ ) __UpperCAmelCase = tokenizer_p.encode_plus(lowercase__ , add_special_tokens=lowercase__ , return_token_type_ids=lowercase__ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) __UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) __UpperCAmelCase = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual( lowercase__ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( lowercase__ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def lowerCAmelCase_ (self ) -> Optional[int]: for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) __UpperCAmelCase = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] , lowercase__ ) self.assertEqual(post_processor_state['''add_prefix_space'''] , lowercase__ ) self.assertEqual(post_processor_state['''trim_offsets'''] , lowercase__ ) def lowerCAmelCase_ (self ) -> Union[str, Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __UpperCAmelCase = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` __UpperCAmelCase = F'''{text_of_1_token} {text_of_1_token}''' __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowercase__ ) + 1, len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowercase__ ) + 1, len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowercase__ ), len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowercase__ ), len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = F''' {text}''' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowercase__ ) + 1, 1 + len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowercase__ ), 1 + len(lowercase__ ) + 1 + len(lowercase__ )) , ) __UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowercase__ , use_fast=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ ) __UpperCAmelCase = tokenizer_r(lowercase__ , return_offsets_mapping=lowercase__ , add_special_tokens=lowercase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowercase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowercase__ ), 1 + len(lowercase__ ) + 1 + len(lowercase__ )) , )
333
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : str = '''new-model''' if is_tf_available(): class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Tuple = NewModelConfig @require_tf class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 'bert-base-cased' __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 'bert-base-cased' __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForPreTraining.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(_A ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(_A ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(_A ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForSequenceClassification.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def _A ( self ): '''simple docstring''' for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForQuestionAnswering.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow @require_tensorflow_probability def _A ( self ): '''simple docstring''' for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained(_A ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained( _A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 14_410 ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 14_410 ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny' ) self.assertIsInstance(_A , _A ) __SCREAMING_SNAKE_CASE = copy.deepcopy(model.config ) __SCREAMING_SNAKE_CASE = ['FunnelBaseModel'] __SCREAMING_SNAKE_CASE = TFAutoModel.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def _A ( self ): '''simple docstring''' try: AutoConfig.register('new-model' , _A ) __SCREAMING_SNAKE_CASE = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) auto_class.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) # Now that the config is registered, it can be used as any other config with the auto-API __SCREAMING_SNAKE_CASE = BertModelTester(self ).get_config() __SCREAMING_SNAKE_CASE = NewModelConfig(**tiny_config.to_dict() ) __SCREAMING_SNAKE_CASE = auto_class.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __SCREAMING_SNAKE_CASE = auto_class.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _A ( self ): '''simple docstring''' with self.assertRaisesRegex( _A , 'bert-base is not a local folder and is not a valid model identifier' ): __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('bert-base' ) def _A ( self ): '''simple docstring''' with self.assertRaisesRegex( _A , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(_A , revision='aaaaaa' ) def _A ( self ): '''simple docstring''' with self.assertRaisesRegex( _A , 'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' , ): __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def _A ( self ): '''simple docstring''' with self.assertRaisesRegex(_A , 'Use `from_pt=True` to load this model' ): __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) with RequestCounter() as counter: __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) with RequestCounter() as counter: __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
118
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def __lowercase ( a__ ) -> List[Any]: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def __lowercase ( ) -> Any: with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" __SCREAMING_SNAKE_CASE = [1, 2, 3] with pytest.raises(a__ ): with parallel_backend('unsupported backend' ): map_nested(a__ , a__ , num_proc=2 ) with pytest.raises(a__ ): with parallel_backend('unsupported backend' ): map_nested(a__ , a__ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc' , [2, -1] ) def __lowercase ( a__ ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = [1, 2] __SCREAMING_SNAKE_CASE = {'a': 1, 'b': 2} __SCREAMING_SNAKE_CASE = {'a': [1, 2], 'b': [3, 4]} __SCREAMING_SNAKE_CASE = {'a': {'1': 1}, 'b': 2} __SCREAMING_SNAKE_CASE = {'a': 1, 'b': 2, 'c': 3, 'd': 4} __SCREAMING_SNAKE_CASE = [2, 3] __SCREAMING_SNAKE_CASE = {'a': 2, 'b': 3} __SCREAMING_SNAKE_CASE = {'a': [2, 3], 'b': [4, 5]} __SCREAMING_SNAKE_CASE = {'a': {'1': 2}, 'b': 3} __SCREAMING_SNAKE_CASE = {'a': 2, 'b': 3, 'c': 4, 'd': 5} with parallel_backend('spark' ): assert map_nested(a__ , a__ , num_proc=a__ ) == expected_map_nested_sa assert map_nested(a__ , a__ , num_proc=a__ ) == expected_map_nested_sa assert map_nested(a__ , a__ , num_proc=a__ ) == expected_map_nested_sa assert map_nested(a__ , a__ , num_proc=a__ ) == expected_map_nested_sa assert map_nested(a__ , a__ , num_proc=a__ ) == expected_map_nested_sa
118
1
import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class lowercase__( unittest.TestCase ): """simple docstring""" def __init__( self : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any]=7 , SCREAMING_SNAKE_CASE_ : Optional[int]=3 , SCREAMING_SNAKE_CASE_ : Any=1_8 , SCREAMING_SNAKE_CASE_ : Tuple=3_0 , SCREAMING_SNAKE_CASE_ : int=4_0_0 , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : str=None , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Optional[Any]=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_ : List[str]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: lowercase_ = size if size is not None else {'''height''': 1_8, '''width''': 1_8} lowercase_ = parent lowercase_ = batch_size lowercase_ = num_channels lowercase_ = image_size lowercase_ = min_resolution lowercase_ = max_resolution lowercase_ = do_resize lowercase_ = size lowercase_ = do_normalize lowercase_ = image_mean lowercase_ = image_std def _lowercase ( self : Tuple ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowercase__( UpperCAmelCase , unittest.TestCase ): """simple docstring""" a :Optional[Any] = DPTImageProcessor if is_vision_available() else None def _lowercase ( self : Any ) -> Union[str, Any]: lowercase_ = DPTImageProcessingTester(self ) @property def _lowercase ( self : Any ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self : int ) -> Dict: lowercase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''image_mean''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''image_std''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''size''' ) ) def _lowercase ( self : Optional[Any] ) -> Optional[int]: lowercase_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 1_8, '''width''': 1_8} ) lowercase_ = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'''height''': 4_2, '''width''': 4_2} ) def _lowercase ( self : Tuple ) -> List[Any]: # Initialize image_processing lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input lowercase_ = 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 lowercase_ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _lowercase ( self : str ) -> Optional[int]: # Initialize image_processing lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input lowercase_ = 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 lowercase_ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _lowercase ( self : List[str] ) -> str: # Initialize image_processing lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input lowercase_ = 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 lowercase_ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , )
30
import re import string import numpy as np import datasets UpperCAmelCase_ : Dict = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCAmelCase_ : Any = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCAmelCase_ : Tuple = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _A ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : int=False , __lowerCamelCase : Optional[int]=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase :str = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in predictions] ) UpperCamelCase :Tuple = np.array([re.sub(__lowerCamelCase , """""" , __lowerCamelCase ) for x in references] ) else: UpperCamelCase :Any = np.asarray(__lowerCamelCase ) UpperCamelCase :str = np.asarray(__lowerCamelCase ) if ignore_case: UpperCamelCase :Tuple = np.char.lower(__lowerCamelCase ) UpperCamelCase :Any = np.char.lower(__lowerCamelCase ) if ignore_punctuation: UpperCamelCase :Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase :Optional[Any] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :List[str] = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) if ignore_numbers: UpperCamelCase :Tuple = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase :Dict = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :Tuple = np.char.translate(__lowerCamelCase , table=__lowerCamelCase ) UpperCamelCase :int = predictions == references return {"exact_match": np.mean(__lowerCamelCase ) * 100}
38
0
from PIL import Image def snake_case_ ( lowerCAmelCase_ : Image , lowerCAmelCase_ : float ): def brightness(lowerCAmelCase_ : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(lowerCAmelCase_ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase : List[str] = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
306
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowercase : Dict = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) __lowercase : List[str] = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" __lowercase : Optional[Any] = model(__a )["""last_hidden_state"""] __lowercase : Any = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , __a ) # compare the actual values for a slice. __lowercase : Dict = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
306
1
"""simple docstring""" from __future__ import annotations def _A ( UpperCamelCase_ : list[int | str]) -> None: '''simple docstring''' create_state_space_tree(UpperCamelCase_, [], 0, [0 for i in range(len(UpperCamelCase_))]) def _A ( UpperCamelCase_ : list[int | str], UpperCamelCase_ : list[int | str], UpperCamelCase_ : int, UpperCamelCase_ : list[int], ) -> None: '''simple docstring''' if index == len(UpperCamelCase_): print(UpperCamelCase_) return for i in range(len(UpperCamelCase_)): if not index_used[i]: current_sequence.append(sequence[i]) __lowercase = True create_state_space_tree(UpperCamelCase_, UpperCamelCase_, index + 1, UpperCamelCase_) current_sequence.pop() __lowercase = False _a = [3, 1, 2, 4] generate_all_permutations(sequence) _a = ["A", "B", "C"] generate_all_permutations(sequence_a)
17
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def __UpperCamelCase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str=False ): __a : Any = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"module.blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"module.blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"module.blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"module.blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"module.blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"module.blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"module.blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"module.blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"module.blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"module.blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" __a : Optional[int] = [(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'''), ] ) return rename_keys def __UpperCamelCase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any]=False ): for i in range(config.num_hidden_layers ): if base_model: __a : Dict = '''''' else: __a : str = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __a : List[Any] = state_dict.pop(f"module.blocks.{i}.attn.qkv.weight" ) __a : Tuple = state_dict.pop(f"module.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __a : Dict = in_proj_weight[ : config.hidden_size, : ] __a : str = in_proj_bias[: config.hidden_size] __a : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __a : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __a : str = in_proj_weight[ -config.hidden_size :, : ] __a : Optional[Any] = in_proj_bias[-config.hidden_size :] def __UpperCamelCase ( lowerCAmelCase__ : Optional[int] ): __a : Dict = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : Optional[Any] ): # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. __a : str = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ): __a : Optional[Any] = dct.pop(lowerCAmelCase__ ) __a : Optional[Any] = val def __UpperCamelCase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ): __a : str = ViTMSNConfig() __a : List[Any] = 1_0_0_0 __a : Union[str, Any] = '''datasets/huggingface/label-files''' __a : Optional[int] = '''imagenet-1k-id2label.json''' __a : Optional[int] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ ) , '''r''' ) ) __a : Dict = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __a : Tuple = idalabel __a : int = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: __a : Union[str, Any] = 3_8_4 __a : Union[str, Any] = 1_5_3_6 __a : Union[str, Any] = 6 elif "l16" in checkpoint_url: __a : str = 1_0_2_4 __a : Union[str, Any] = 4_0_9_6 __a : Optional[int] = 2_4 __a : int = 1_6 __a : List[Any] = 0.1 elif "b4" in checkpoint_url: __a : int = 4 elif "l7" in checkpoint_url: __a : int = 7 __a : List[Any] = 1_0_2_4 __a : Union[str, Any] = 4_0_9_6 __a : List[str] = 2_4 __a : int = 1_6 __a : Tuple = 0.1 __a : Dict = ViTMSNModel(lowerCAmelCase__ ) __a : Union[str, Any] = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' )['''target_encoder'''] __a : Optional[int] = ViTImageProcessor(size=config.image_size ) remove_projection_head(lowerCAmelCase__ ) __a : str = create_rename_keys(lowerCAmelCase__ , base_model=lowerCAmelCase__ ) for src, dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) read_in_q_k_v(lowerCAmelCase__ , lowerCAmelCase__ , base_model=lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) model.eval() __a : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __a : str = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) __a : Any = ViTImageProcessor( size=config.image_size , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ ) __a : Tuple = image_processor(images=lowerCAmelCase__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) __a : str = model(**lowerCAmelCase__ ) __a : List[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: __a : Dict = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] ) elif "b16" in checkpoint_url: __a : List[str] = torch.tensor([[14.28_89, -18.90_45, 11.72_81]] ) elif "l16" in checkpoint_url: __a : str = torch.tensor([[41.50_28, -22.86_81, 45.64_75]] ) elif "b4" in checkpoint_url: __a : Union[str, Any] = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] ) else: __a : Dict = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , lowerCAmelCase__ , atol=1e-4 ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(lowerCAmelCase__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowercase__ =argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase__ =parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
216
0
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if hor == 128: A : Optional[int] = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') A : str = (32, 128, 256) A : Union[str, Any] = ('''UpResnetBlock1D''', '''UpResnetBlock1D''') elif hor == 32: A : Union[str, Any] = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''') A : Any = (32, 64, 128, 256) A : Any = ('''UpResnetBlock1D''', '''UpResnetBlock1D''', '''UpResnetBlock1D''') A : Optional[Any] = torch.load(F'/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch' ) A : str = model.state_dict() A : Optional[int] = { '''down_block_types''': down_block_types, '''block_out_channels''': block_out_channels, '''up_block_types''': up_block_types, '''layers_per_block''': 1, '''use_timestep_embedding''': True, '''out_block_type''': '''OutConv1DBlock''', '''norm_num_groups''': 8, '''downsample_each_block''': False, '''in_channels''': 14, '''out_channels''': 14, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''sample_size''': 6_5536, '''mid_block_type''': '''MidResTemporalBlock1D''', '''act_fn''': '''mish''', } A : Optional[Any] = UNetaDModel(**snake_case__ ) print(F'length of state dict: {len(state_dict.keys() )}' ) print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' ) A : Union[str, Any] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): A : Union[str, Any] = state_dict.pop(snake_case__ ) hf_value_function.load_state_dict(snake_case__ ) torch.save(hf_value_function.state_dict() , F'hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin' ) with open(F'hub/hopper-medium-v2/unet/hor{hor}/config.json' , '''w''' ) as f: json.dump(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( ): '''simple docstring''' A : int = { '''in_channels''': 14, '''down_block_types''': ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''), '''up_block_types''': (), '''out_block_type''': '''ValueFunction''', '''mid_block_type''': '''ValueFunctionMidBlock1D''', '''block_out_channels''': (32, 64, 128, 256), '''layers_per_block''': 1, '''downsample_each_block''': True, '''sample_size''': 6_5536, '''out_channels''': 14, '''extra_in_channels''': 0, '''time_embedding_type''': '''positional''', '''use_timestep_embedding''': True, '''flip_sin_to_cos''': False, '''freq_shift''': 1, '''norm_num_groups''': 8, '''act_fn''': '''mish''', } A : Optional[Any] = torch.load('''/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch''' ) A : Optional[int] = model A : List[Any] = UNetaDModel(**snake_case__ ) print(F'length of state dict: {len(state_dict.keys() )}' ) print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' ) A : Union[str, Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): A : int = state_dict.pop(snake_case__ ) hf_value_function.load_state_dict(snake_case__ ) torch.save(hf_value_function.state_dict() , '''hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin''' ) with open('''hub/hopper-medium-v2/value_function/config.json''' , '''w''' ) as f: json.dump(snake_case__ , snake_case__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
from __future__ import annotations _lowerCAmelCase : Dict = tuple[int, int, int] _lowerCAmelCase : Optional[Any] = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase _lowerCAmelCase : Union[str, Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- _lowerCAmelCase : List[Any] = '''EGZWVONAHDCLFQMSIPJBYUKXTR''' _lowerCAmelCase : Any = '''FOBHMDKEXQNRAULPGSJVTYICZW''' _lowerCAmelCase : Union[str, Any] = '''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- _lowerCAmelCase : List[Any] = { '''A''': '''N''', '''N''': '''A''', '''B''': '''O''', '''O''': '''B''', '''C''': '''P''', '''P''': '''C''', '''D''': '''Q''', '''Q''': '''D''', '''E''': '''R''', '''R''': '''E''', '''F''': '''S''', '''S''': '''F''', '''G''': '''T''', '''T''': '''G''', '''H''': '''U''', '''U''': '''H''', '''I''': '''V''', '''V''': '''I''', '''J''': '''W''', '''W''': '''J''', '''K''': '''X''', '''X''': '''K''', '''L''': '''Y''', '''Y''': '''L''', '''M''': '''Z''', '''Z''': '''M''', } # -------------------------- extra rotors -------------------------- _lowerCAmelCase : List[Any] = '''RMDJXFUWGISLHVTCQNKYPBEZOA''' _lowerCAmelCase : Union[str, Any] = '''SGLCPQWZHKXAREONTFBVIYJUDM''' _lowerCAmelCase : List[Any] = '''HVSICLTYKQUBXDWAJZOMFGPREN''' _lowerCAmelCase : Optional[Any] = '''RZWQHFMVDBKICJLNTUXAGYPSOE''' _lowerCAmelCase : List[Any] = '''LFKIJODBEGAMQPXVUHYSTCZRWN''' _lowerCAmelCase : Dict = '''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def __snake_case ( _lowerCAmelCase : RotorPositionT , _lowerCAmelCase : RotorSelectionT , _lowerCAmelCase : str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(_lowerCAmelCase ) )) < 3: A_ : List[Any] = f"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(_lowerCAmelCase ) # Checks if rotor positions are valid A_ , A_ , A_ : List[str] = rotpos if not 0 < rotorposa <= len(_lowerCAmelCase ): A_ : str = f"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(_lowerCAmelCase ) if not 0 < rotorposa <= len(_lowerCAmelCase ): A_ : str = f"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_lowerCAmelCase ) if not 0 < rotorposa <= len(_lowerCAmelCase ): A_ : str = f"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(_lowerCAmelCase ) # Validates string and returns dict A_ : Optional[Any] = _plugboard(_lowerCAmelCase ) return rotpos, rotsel, pbdict def __snake_case ( _lowerCAmelCase : str ) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): A_ : Union[str, Any] = f"Plugboard setting isn't type string ({type(_lowerCAmelCase )})" raise TypeError(_lowerCAmelCase ) elif len(_lowerCAmelCase ) % 2 != 0: A_ : Union[str, Any] = f"Odd number of symbols ({len(_lowerCAmelCase )})" raise Exception(_lowerCAmelCase ) elif pbstring == "": return {} pbstring.replace(" " , "" ) # Checks if all characters are unique A_ : Dict = set() for i in pbstring: if i not in abc: A_ : Union[str, Any] = f"'{i}' not in list of symbols" raise Exception(_lowerCAmelCase ) elif i in tmppbl: A_ : str = f"Duplicate symbol ({i})" raise Exception(_lowerCAmelCase ) else: tmppbl.add(_lowerCAmelCase ) del tmppbl # Created the dictionary A_ : str = {} for j in range(0 , len(_lowerCAmelCase ) - 1 , 2 ): A_ : Optional[Any] = pbstring[j + 1] A_ : Dict = pbstring[j] return pb def __snake_case ( _lowerCAmelCase : str , _lowerCAmelCase : RotorPositionT , _lowerCAmelCase : RotorSelectionT = (rotora, rotora, rotora) , _lowerCAmelCase : str = "" , ) -> str: A_ : str = text.upper() A_ , A_ , A_ : int = _validator( _lowerCAmelCase , _lowerCAmelCase , plugb.upper() ) A_ , A_ , A_ : int = rotor_position A_ , A_ , A_ : str = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 A_ : str = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: A_ : Any = plugboard[symbol] # rotor ra -------------------------- A_ : List[Any] = abc.index(_lowerCAmelCase ) + rotorposa A_ : List[str] = rotora[index % len(_lowerCAmelCase )] # rotor rb -------------------------- A_ : List[Any] = abc.index(_lowerCAmelCase ) + rotorposa A_ : Optional[int] = rotora[index % len(_lowerCAmelCase )] # rotor rc -------------------------- A_ : Any = abc.index(_lowerCAmelCase ) + rotorposa A_ : Tuple = rotora[index % len(_lowerCAmelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher A_ : int = reflector[symbol] # 2nd rotors A_ : Tuple = abc[rotora.index(_lowerCAmelCase ) - rotorposa] A_ : Union[str, Any] = abc[rotora.index(_lowerCAmelCase ) - rotorposa] A_ : Optional[Any] = abc[rotora.index(_lowerCAmelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: A_ : Any = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_lowerCAmelCase ): A_ : List[Any] = 0 rotorposa += 1 if rotorposa >= len(_lowerCAmelCase ): A_ : Union[str, Any] = 0 rotorposa += 1 if rotorposa >= len(_lowerCAmelCase ): A_ : str = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_lowerCAmelCase ) return "".join(_lowerCAmelCase ) if __name__ == "__main__": _lowerCAmelCase : Union[str, Any] = '''This is my Python script that emulates the Enigma machine from WWII.''' _lowerCAmelCase : Tuple = (1, 1, 1) _lowerCAmelCase : List[str] = '''pictures''' _lowerCAmelCase : str = (rotora, rotora, rotora) _lowerCAmelCase : int = enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
300
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : Optional[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_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } _lowerCAmelCase : int = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def __snake_case ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int ) -> List[Any]: for attribute in key.split("." ): A_ : List[Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) if weight_type is not None: A_ : List[Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape else: A_ : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": A_ : Optional[int] = value elif weight_type == "weight_g": A_ : Optional[int] = value elif weight_type == "weight_v": A_ : Any = value elif weight_type == "bias": A_ : str = value else: A_ : Any = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __snake_case ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Dict ) -> List[str]: A_ : Optional[Any] = [] A_ : Any = fairseq_model.state_dict() A_ : Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight A_ : str = None for name, value in fairseq_dict.items(): A_ : Tuple = False if "conv_layers" in name: load_conv_layer( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == "group" , ) A_ : Optional[Any] = True elif name.split("." )[0] == "proj": A_ : Dict = fairseq_model.proj A_ : List[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: A_ : int = True if "*" in mapped_key: A_ : Optional[Any] = name.split(_lowerCAmelCase )[0].split("." )[-2] A_ : int = mapped_key.replace("*" , _lowerCAmelCase ) if "weight_g" in name: A_ : List[Any] = "weight_g" elif "weight_v" in name: A_ : List[Any] = "weight_v" elif "bias" in name: A_ : Dict = "bias" elif "weight" in name: A_ : List[Any] = "weight" else: A_ : Dict = None set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) continue if not is_used: unused_weights.append(_lowerCAmelCase ) logger.warning(f"Unused weights: {unused_weights}" ) return proj_weight def __snake_case ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[int] ) -> str: A_ : Any = full_name.split("conv_layers." )[-1] A_ : Optional[int] = name.split("." ) A_ : Optional[Any] = int(items[0] ) A_ : Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) A_ : List[Any] = 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_ : int = 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_ : List[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." ) A_ : Tuple = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_lowerCAmelCase ) def __snake_case ( _lowerCAmelCase : Optional[int] ) -> str: A_ , A_ : List[str] = emb.weight.shape A_ : Optional[int] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase , bias=_lowerCAmelCase ) A_ : List[Any] = emb.weight.data return lin_layer def __snake_case ( _lowerCAmelCase : str ) -> Tuple: with open(_lowerCAmelCase , "r" , encoding="utf-8" ) as f: A_ : int = f.readlines() A_ : Dict = [line.split(" " )[0] for line in lines] A_ : Tuple = len(_lowerCAmelCase ) A_ : Union[str, Any] = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(_lowerCAmelCase , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def __snake_case ( _lowerCAmelCase : int , _lowerCAmelCase : Tuple , _lowerCAmelCase : Dict , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] , _lowerCAmelCase : Dict , ) -> Tuple: A_ : Optional[int] = WavaVecaConfig.from_pretrained(_lowerCAmelCase ) A_ : str = SpeechaTextaConfig.from_pretrained( _lowerCAmelCase , vocab_size=_lowerCAmelCase , decoder_layers=_lowerCAmelCase , do_stable_layer_norm=_lowerCAmelCase ) A_ : int = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , ) A_ , A_ , A_ : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) A_ : Union[str, Any] = model[0].eval() # set weights for wav2vec2 encoder A_ : Tuple = WavaVecaModel(_lowerCAmelCase ) A_ : str = recursively_load_weights_wavaveca(model.encoder , _lowerCAmelCase ) A_ : Tuple = SpeechaTextaForCausalLM(_lowerCAmelCase ) A_ , A_ : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_lowerCAmelCase ) # set output linear layer unexpected_keys.remove("embed_out" ) A_ : Union[str, Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) A_ : str = SpeechEncoderDecoderModel(encoder=_lowerCAmelCase , decoder=_lowerCAmelCase ) A_ : Optional[Any] = False # add projection layer A_ : Optional[Any] = nn.Parameter(projection_layer.weight ) A_ : int = nn.Parameter(projection_layer.bias ) A_ : str = create_vocab_dict(_lowerCAmelCase ) with open(os.path.join(_lowerCAmelCase , "vocab.json" ) , "w" ) as fp: json.dump(_lowerCAmelCase , _lowerCAmelCase ) A_ : Any = SpeechaTextaTokenizer(os.path.join(_lowerCAmelCase , "vocab.json" ) ) tokenizer.save_pretrained(_lowerCAmelCase ) A_ : Optional[int] = hf_wavavec.config.to_dict() A_ : int = tokenizer.pad_token_id A_ : List[str] = tokenizer.bos_token_id A_ : List[str] = tokenizer.eos_token_id A_ : List[str] = "speech_to_text_2" A_ : Tuple = "wav2vec2" A_ : str = SpeechEncoderDecoderConfig.from_dict(_lowerCAmelCase ) hf_wavavec.save_pretrained(_lowerCAmelCase ) feature_extractor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": _lowerCAmelCase : Optional[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( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=10_224, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') _lowerCAmelCase : Union[str, Any] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
300
1
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __A : Tuple = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : Optional[int] = nn.ModuleList(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , ): for i, (image, scale, controlnet) in enumerate(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.nets ) ): UpperCamelCase : str = controlnet( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # merge samples if i == 0: UpperCamelCase : List[str] = down_samples, mid_sample else: UpperCamelCase : int = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , ): UpperCamelCase : Dict = 0 UpperCamelCase : Any = save_directory for controlnet in self.nets: controlnet.save_pretrained( SCREAMING_SNAKE_CASE_ , is_main_process=SCREAMING_SNAKE_CASE_ , save_function=SCREAMING_SNAKE_CASE_ , safe_serialization=SCREAMING_SNAKE_CASE_ , variant=SCREAMING_SNAKE_CASE_ , ) idx += 1 UpperCamelCase : str = model_path_to_save + f'_{idx}' @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = 0 UpperCamelCase : Optional[int] = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... UpperCamelCase : Tuple = pretrained_model_path while os.path.isdir(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = ControlNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) controlnets.append(SCREAMING_SNAKE_CASE_ ) idx += 1 UpperCamelCase : Tuple = pretrained_model_path + f'_{idx}' logger.info(f'{len(SCREAMING_SNAKE_CASE_ )} controlnets loaded from {pretrained_model_path}.' ) if len(SCREAMING_SNAKE_CASE_ ) == 0: raise ValueError( f'No ControlNets found under {os.path.dirname(SCREAMING_SNAKE_CASE_ )}. Expected at least {pretrained_model_path + "_0"}.' ) return cls(SCREAMING_SNAKE_CASE_ )
367
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = 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_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. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCAmelCase__ : Any =logging.get_logger(__name__) class UpperCAmelCase_ ( snake_case_ ): '''simple docstring''' UpperCamelCase__ : Optional[Any] = ['''pixel_values'''] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , **_A , ): '''simple docstring''' super().__init__(**_A ) __SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 256} __SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {'height': 224, 'width': 224} __SCREAMING_SNAKE_CASE = get_size_dict(_A ) __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = resample __SCREAMING_SNAKE_CASE = do_center_crop __SCREAMING_SNAKE_CASE = crop_size __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self , _A , _A , _A = PILImageResampling.BICUBIC , _A = None , **_A , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) __SCREAMING_SNAKE_CASE = get_resize_output_image_size(_A , size=size['shortest_edge'] , default_to_square=_A ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def _A ( self , _A , _A , _A = None , **_A , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_size_dict(_A ) return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A ) def _A ( self , _A , _A , _A = None , **_A ): '''simple docstring''' return rescale(_A , scale=_A , data_format=_A , **_A ) def _A ( self , _A , _A , _A , _A = None , **_A , ): '''simple docstring''' return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def _A ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE = size if size is not None else self.size __SCREAMING_SNAKE_CASE = get_size_dict(_A , default_to_square=_A ) __SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE = do_center_crop if do_center_crop is not None else self.do_center_crop __SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else self.crop_size __SCREAMING_SNAKE_CASE = get_size_dict(_A ) __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE = make_list_of_images(_A ) if not valid_images(_A ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE = [to_numpy_array(_A ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE = [self.resize(image=_A , size=_A , resample=_A ) for image in images] if do_center_crop: __SCREAMING_SNAKE_CASE = [self.center_crop(image=_A , size=_A ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: __SCREAMING_SNAKE_CASE = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(_A , _A ) for image in images] __SCREAMING_SNAKE_CASE = {'pixel_values': images} return BatchFeature(data=_A , tensor_type=_A )
257
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging __A =logging.get_logger(__name__) # pylint: disable=invalid-name class _SCREAMING_SNAKE_CASE ( snake_case_ ): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> List[Any]: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: lowerCamelCase_ = ( f'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' f' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , lowercase , standard_warn=lowercase ) lowerCamelCase_ = dict(scheduler.config ) lowerCamelCase_ = 1 lowerCamelCase_ = FrozenDict(lowercase ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: lowerCamelCase_ = ( f'The configuration file of this scheduler: {scheduler} has not set the configuration' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , lowercase , standard_warn=lowercase ) lowerCamelCase_ = dict(scheduler.config ) lowerCamelCase_ = True lowerCamelCase_ = FrozenDict(lowercase ) if safety_checker is None: logger.warning( f'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=lowercase , segmentation_processor=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , unet=lowercase , scheduler=lowercase , safety_checker=lowercase , feature_extractor=lowercase , ) def SCREAMING_SNAKE_CASE_( self , lowercase = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: self.enable_attention_slicing(lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> str: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) lowerCamelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(lowercase , lowercase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowercase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , lowercase , lowercase , lowercase , lowercase = 512 , lowercase = 512 , lowercase = 50 , lowercase = 7.5 , lowercase = None , lowercase = 1 , lowercase = 0.0 , lowercase = None , lowercase = None , lowercase = "pil" , lowercase = True , lowercase = None , lowercase = 1 , **lowercase , ) -> int: lowerCamelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) lowerCamelCase_ = self.segmentation_model(**lowercase ) lowerCamelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() lowerCamelCase_ = self.numpy_to_pil(lowercase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask lowerCamelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=lowercase , image=lowercase , mask_image=lowercase , height=lowercase , width=lowercase , num_inference_steps=lowercase , guidance_scale=lowercase , negative_prompt=lowercase , num_images_per_prompt=lowercase , eta=lowercase , generator=lowercase , latents=lowercase , output_type=lowercase , return_dict=lowercase , callback=lowercase , callback_steps=lowercase , )
19
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "yolos" def __init__( self : str , SCREAMING_SNAKE_CASE__ : Union[str, Any]=768 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : List[Any]=12 , SCREAMING_SNAKE_CASE__ : Tuple=3_072 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-1_2 , SCREAMING_SNAKE_CASE__ : Optional[int]=[512, 864] , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : str=100 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Any=5 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias lowerCAmelCase__ = num_detection_tokens lowerCAmelCase__ = use_mid_position_embeddings lowerCAmelCase__ = auxiliary_loss # Hungarian matcher lowerCAmelCase__ = class_cost lowerCAmelCase__ = bbox_cost lowerCAmelCase__ = giou_cost # Loss coefficients lowerCAmelCase__ = bbox_loss_coefficient lowerCAmelCase__ = giou_loss_coefficient lowerCAmelCase__ = eos_coefficient class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = version.parse("1.11" ) @property def a ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def a ( self : List[str] ) -> float: return 1e-4 @property def a ( self : Tuple ) -> int: return 12
221
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# UpperCamelCase = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] UpperCamelCase = [ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] UpperCamelCase = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks UpperCamelCase = F"""down_blocks.{i}.resnets.{j}.""" UpperCamelCase = F"""input_blocks.{3*i + j + 1}.0.""" unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 UpperCamelCase = F"""down_blocks.{i}.attentions.{j}.""" UpperCamelCase = F"""input_blocks.{3*i + j + 1}.1.""" unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks UpperCamelCase = F"""up_blocks.{i}.resnets.{j}.""" UpperCamelCase = F"""output_blocks.{3*i + j}.0.""" unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 UpperCamelCase = F"""up_blocks.{i}.attentions.{j}.""" UpperCamelCase = F"""output_blocks.{3*i + j}.1.""" unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 UpperCamelCase = F"""down_blocks.{i}.downsamplers.0.conv.""" UpperCamelCase = F"""input_blocks.{3*(i+1)}.0.op.""" unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 UpperCamelCase = F"""up_blocks.{i}.upsamplers.0.""" UpperCamelCase = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}.""" unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) UpperCamelCase = 'mid_block.attentions.0.' UpperCamelCase = 'middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): UpperCamelCase = F"""mid_block.resnets.{j}.""" UpperCamelCase = F"""middle_block.{2*j}.""" unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def _A ( lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: lowerCAmelCase__ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: lowerCAmelCase__ = v.replace(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: lowerCAmelCase__ = v.replace(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = v lowerCAmelCase__ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# UpperCamelCase = [ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): UpperCamelCase = F"""encoder.down_blocks.{i}.resnets.{j}.""" UpperCamelCase = F"""encoder.down.{i}.block.{j}.""" vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: UpperCamelCase = F"""down_blocks.{i}.downsamplers.0.""" UpperCamelCase = F"""down.{i}.downsample.""" vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) UpperCamelCase = F"""up_blocks.{i}.upsamplers.0.""" UpperCamelCase = F"""up.{3-i}.upsample.""" vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): UpperCamelCase = F"""decoder.up_blocks.{i}.resnets.{j}.""" UpperCamelCase = F"""decoder.up.{3-i}.block.{j}.""" vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): UpperCamelCase = F"""mid_block.resnets.{i}.""" UpperCamelCase = F"""mid.block_{i+1}.""" vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) UpperCamelCase = [ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def _A ( lowerCAmelCase_ : List[str] ): """simple docstring""" return w.reshape(*w.shape , 1 , 1 ) def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" lowerCAmelCase__ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: lowerCAmelCase__ = v.replace(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: lowerCAmelCase__ = v.replace(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = v lowerCAmelCase__ = {v: vae_state_dict[k] for k, v in mapping.items()} lowerCAmelCase__ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if F'mid.attn_1.{weight_name}.weight' in k: print(F'Reshaping {k} for SD format' ) lowerCAmelCase__ = reshape_weight_for_sd(lowerCAmelCase_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# UpperCamelCase = [ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] UpperCamelCase = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} UpperCamelCase = re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp UpperCamelCase = {'q': 0, 'k': 1, 'v': 2} def _A ( lowerCAmelCase_ : Dict ): """simple docstring""" lowerCAmelCase__ = {} lowerCAmelCase__ = {} lowerCAmelCase__ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): lowerCAmelCase__ = k[: -len(".q_proj.weight" )] lowerCAmelCase__ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: lowerCAmelCase__ = [None, None, None] lowerCAmelCase__ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): lowerCAmelCase__ = k[: -len(".q_proj.bias" )] lowerCAmelCase__ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: lowerCAmelCase__ = [None, None, None] lowerCAmelCase__ = v continue lowerCAmelCase__ = textenc_pattern.sub(lambda lowerCAmelCase_ : protected[re.escape(m.group(0 ) )] , lowerCAmelCase_ ) lowerCAmelCase__ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) lowerCAmelCase__ = textenc_pattern.sub(lambda lowerCAmelCase_ : protected[re.escape(m.group(0 ) )] , lowerCAmelCase_ ) lowerCAmelCase__ = torch.cat(lowerCAmelCase_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) lowerCAmelCase__ = textenc_pattern.sub(lambda lowerCAmelCase_ : protected[re.escape(m.group(0 ) )] , lowerCAmelCase_ ) lowerCAmelCase__ = torch.cat(lowerCAmelCase_ ) return new_state_dict def _A ( lowerCAmelCase_ : Any ): """simple docstring""" return text_enc_dict if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) UpperCamelCase = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors UpperCamelCase = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') UpperCamelCase = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') UpperCamelCase = osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): UpperCamelCase = load_file(unet_path, device='cpu') else: UpperCamelCase = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') UpperCamelCase = torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): UpperCamelCase = load_file(vae_path, device='cpu') else: UpperCamelCase = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') UpperCamelCase = torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): UpperCamelCase = load_file(text_enc_path, device='cpu') else: UpperCamelCase = osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') UpperCamelCase = torch.load(text_enc_path, map_location='cpu') # Convert the UNet model UpperCamelCase = convert_unet_state_dict(unet_state_dict) UpperCamelCase = {'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model UpperCamelCase = convert_vae_state_dict(vae_state_dict) UpperCamelCase = {'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper UpperCamelCase = 'text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm UpperCamelCase = {'transformer.' + k: v for k, v in text_enc_dict.items()} UpperCamelCase = convert_text_enc_state_dict_vaa(text_enc_dict) UpperCamelCase = {'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: UpperCamelCase = convert_text_enc_state_dict(text_enc_dict) UpperCamelCase = {'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint UpperCamelCase = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: UpperCamelCase = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: UpperCamelCase = {'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
221
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowercase__ = logging.get_logger(__name__) class lowerCAmelCase__ ( lowercase ): '''simple docstring''' def __init__( self , *lowercase , **lowercase ): warnings.warn( 'The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DPTImageProcessor instead.' , lowercase , ) super().__init__(*lowercase , **lowercase )
96
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowercase__ = 16 lowercase__ = 32 def _snake_case ( lowercase__ , lowercase__ = 16 , lowercase__ = "bert-base-cased" ): _lowerCamelCase : List[Any] = AutoTokenizer.from_pretrained(lowercase__ ) _lowerCamelCase : Tuple = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowercase__ ): # max_length=None => use the model max length (it's actually the default) _lowerCamelCase : Union[str, Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowercase__ , max_length=lowercase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _lowerCamelCase : int = datasets.map( lowercase__ , batched=lowercase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=lowercase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCamelCase : Optional[int] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowercase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(lowercase__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. _lowerCamelCase : List[str] = DataLoader( tokenized_datasets['train'] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) _lowerCamelCase : int = DataLoader( tokenized_datasets['validation'] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) return train_dataloader, eval_dataloader def _snake_case ( lowercase__ , lowercase__ ): # Initialize accelerator _lowerCamelCase : Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCamelCase : Optional[int] = config['lr'] _lowerCamelCase : Optional[int] = int(config['num_epochs'] ) _lowerCamelCase : Union[str, Any] = int(config['seed'] ) _lowerCamelCase : Optional[int] = int(config['batch_size'] ) _lowerCamelCase : Dict = args.model_name_or_path set_seed(lowercase__ ) _lowerCamelCase, _lowerCamelCase : Optional[int] = get_dataloaders(lowercase__ , lowercase__ , lowercase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCamelCase : int = AutoModelForSequenceClassification.from_pretrained(lowercase__ , return_dict=lowercase__ ) # Instantiate optimizer _lowerCamelCase : Optional[int] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _lowerCamelCase : Union[str, Any] = optimizer_cls(params=model.parameters() , lr=lowercase__ ) if accelerator.state.deepspeed_plugin is not None: _lowerCamelCase : str = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: _lowerCamelCase : Tuple = 1 _lowerCamelCase : List[Any] = (len(lowercase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _lowerCamelCase : Tuple = get_linear_schedule_with_warmup( optimizer=lowercase__ , num_warmup_steps=0 , num_training_steps=lowercase__ , ) else: _lowerCamelCase : Any = DummyScheduler(lowercase__ , total_num_steps=lowercase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Union[str, Any] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) # We need to keep track of how many total steps we have iterated over _lowerCamelCase : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly _lowerCamelCase : Dict = 0 # Now we train the model _lowerCamelCase : Dict = evaluate.load('glue' , 'mrpc' ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : str = {} for epoch in range(lowercase__ , lowercase__ ): model.train() for step, batch in enumerate(lowercase__ ): _lowerCamelCase : List[Any] = model(**lowercase__ ) _lowerCamelCase : int = outputs.loss _lowerCamelCase : Dict = loss / gradient_accumulation_steps accelerator.backward(lowercase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _lowerCamelCase : Union[str, Any] = 0 for step, batch in enumerate(lowercase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCamelCase : Optional[int] = model(**lowercase__ ) _lowerCamelCase : Dict = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _lowerCamelCase, _lowerCamelCase : List[str] = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase__ ) - 1: _lowerCamelCase : Optional[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] _lowerCamelCase : Dict = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase__ , references=lowercase__ , ) _lowerCamelCase : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowercase__ ) _lowerCamelCase : Tuple = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: _lowerCamelCase : str = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(lowercase__ , lowercase__ ) def _snake_case ( ): _lowerCamelCase : Any = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=lowercase__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=lowercase__ , ) parser.add_argument( '--output_dir' , type=lowercase__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=lowercase__ , default=lowercase__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=lowercase__ , default=3 , help='Number of train epochs.' , ) _lowerCamelCase : Optional[Any] = parser.parse_args() _lowerCamelCase : str = {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase__ , lowercase__ ) if __name__ == "__main__": main()
96
1
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( "The RoBERTa Model transformer with early exiting (DeeRoBERTa). " , UpperCAmelCase__ , ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = RobertaConfig __UpperCamelCase = "roberta" def __init__( self : List[str] , lowercase_ : Tuple): '''simple docstring''' super().__init__(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = RobertaEmbeddings(lowercase_) self.init_weights() @add_start_docstrings( "RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. " , UpperCAmelCase__ , ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = RobertaConfig __UpperCamelCase = "roberta" def __init__( self : Any , lowercase_ : List[str]): '''simple docstring''' super().__init__(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = config.num_labels SCREAMING_SNAKE_CASE_ : List[str] = config.num_hidden_layers SCREAMING_SNAKE_CASE_ : int = DeeRobertaModel(lowercase_) SCREAMING_SNAKE_CASE_ : Any = nn.Dropout(config.hidden_dropout_prob) SCREAMING_SNAKE_CASE_ : Tuple = nn.Linear(config.hidden_size , self.config.num_labels) @add_start_docstrings_to_model_forward(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=None , lowercase_ : Dict=None , lowercase_ : str=None , lowercase_ : Tuple=None , lowercase_ : Dict=None , lowercase_ : Optional[int]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Dict=-1 , lowercase_ : str=False , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.num_layers try: SCREAMING_SNAKE_CASE_ : Dict = self.roberta( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , position_ids=lowercase_ , head_mask=lowercase_ , inputs_embeds=lowercase_ , ) SCREAMING_SNAKE_CASE_ : Dict = outputs[1] SCREAMING_SNAKE_CASE_ : List[str] = self.dropout(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.classifier(lowercase_) SCREAMING_SNAKE_CASE_ : int = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: SCREAMING_SNAKE_CASE_ : List[Any] = e.message SCREAMING_SNAKE_CASE_ : List[Any] = e.exit_layer SCREAMING_SNAKE_CASE_ : List[str] = outputs[0] if not self.training: SCREAMING_SNAKE_CASE_ : Dict = entropy(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Dict = [] if labels is not None: if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE_ : Optional[Any] = MSELoss() SCREAMING_SNAKE_CASE_ : Optional[int] = loss_fct(logits.view(-1) , labels.view(-1)) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = CrossEntropyLoss() SCREAMING_SNAKE_CASE_ : Union[str, Any] = loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1)) # work with highway exits SCREAMING_SNAKE_CASE_ : Tuple = [] for highway_exit in outputs[-1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = highway_exit[0] if not self.training: highway_logits_all.append(lowercase_) highway_entropy.append(highway_exit[2]) if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE_ : Optional[Any] = MSELoss() SCREAMING_SNAKE_CASE_ : List[Any] = loss_fct(highway_logits.view(-1) , labels.view(-1)) else: SCREAMING_SNAKE_CASE_ : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE_ : Any = loss_fct(highway_logits.view(-1 , self.num_labels) , labels.view(-1)) highway_losses.append(lowercase_) if train_highway: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (sum(highway_losses[:-1]),) + outputs # exclude the final highway, of course else: SCREAMING_SNAKE_CASE_ : Dict = (loss,) + outputs if not self.training: SCREAMING_SNAKE_CASE_ : Tuple = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: SCREAMING_SNAKE_CASE_ : int = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
366
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
318
0
'''simple docstring''' from heapq import heappop, heappush import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> tuple[float | int, list[tuple[int, int]]]: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = grid.shape lowerCamelCase__ : List[str] = [-1, 1, 0, 0] lowerCamelCase__ : Dict = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] lowerCamelCase__ , lowerCamelCase__ : Any = [(0, source)], set() lowerCamelCase__ : Tuple = np.full((rows, cols) , np.inf ) lowerCamelCase__ : List[str] = 0 lowerCamelCase__ : Optional[int] = np.empty((rows, cols) , dtype=UpperCamelCase ) lowerCamelCase__ : str = None while queue: ((lowerCamelCase__) , (lowerCamelCase__)) : List[str] = heappop(UpperCamelCase ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: lowerCamelCase__ : Optional[int] = [] while (x, y) != source: path.append((x, y) ) lowerCamelCase__ , lowerCamelCase__ : List[Any] = predecessors[x, y] path.append(UpperCamelCase ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(UpperCamelCase ) ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: lowerCamelCase__ : Any = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(UpperCamelCase , (dist + 1, (nx, ny)) ) lowerCamelCase__ : Union[str, Any] = dist + 1 lowerCamelCase__ : List[str] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
41
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() _A : List[Any] =logging.get_logger(__name__) _A : Dict =['''model.decoder.embed_positions.weights'''] def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: if "emb" in name: lowerCamelCase__ : Dict = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: lowerCamelCase__ : List[str] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: lowerCamelCase__ : List[str] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: lowerCamelCase__ : Optional[int] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: lowerCamelCase__ : Union[str, Any] = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: lowerCamelCase__ : Dict = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: lowerCamelCase__ : Optional[Any] = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: lowerCamelCase__ : Dict = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: lowerCamelCase__ : Optional[Any] = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: lowerCamelCase__ : Optional[Any] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: lowerCamelCase__ : int = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Tuple[Dict, Dict]: lowerCamelCase__ : int = list(state_dict.keys() ) lowerCamelCase__ : Tuple = {} for key in keys: lowerCamelCase__ : Any = state_dict.pop(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = rename_keys(UpperCamelCase ) if "in_proj_weight" in key: # split fused qkv proj lowerCamelCase__ : Union[str, Any] = val[:hidden_size, :] lowerCamelCase__ : Any = val[hidden_size : 2 * hidden_size, :] lowerCamelCase__ : Optional[int] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: lowerCamelCase__ : str = val else: lowerCamelCase__ : Union[str, Any] = val return state_dict, enc_dec_proj_state_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values lowerCamelCase__ : int = 1024 lowerCamelCase__ : int = 24 lowerCamelCase__ : List[Any] = 16 elif checkpoint == "medium": lowerCamelCase__ : Any = 1536 lowerCamelCase__ : Union[str, Any] = 48 lowerCamelCase__ : Optional[int] = 24 elif checkpoint == "large": lowerCamelCase__ : Optional[Any] = 2048 lowerCamelCase__ : Dict = 48 lowerCamelCase__ : List[Any] = 32 else: raise ValueError(f'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) lowerCamelCase__ : Any = MusicgenDecoderConfig( hidden_size=UpperCamelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=UpperCamelCase , num_attention_heads=UpperCamelCase , ) return config @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase="cpu" ) -> Optional[Any]: lowerCamelCase__ : Optional[int] = MusicGen.get_pretrained(UpperCamelCase , device=UpperCamelCase ) lowerCamelCase__ : List[Any] = decoder_config_from_checkpoint(UpperCamelCase ) lowerCamelCase__ : Any = fairseq_model.lm.state_dict() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = rename_state_dict( UpperCamelCase , hidden_size=decoder_config.hidden_size ) lowerCamelCase__ : str = TaEncoderModel.from_pretrained("""t5-base""" ) lowerCamelCase__ : Tuple = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) lowerCamelCase__ : Optional[int] = MusicgenForCausalLM(UpperCamelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection lowerCamelCase__ , lowerCamelCase__ : List[str] = decoder.load_state_dict(UpperCamelCase , strict=UpperCamelCase ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(UpperCamelCase ) if len(UpperCamelCase ) > 0: raise ValueError(f'''Missing key(s) in state_dict: {missing_keys}''' ) if len(UpperCamelCase ) > 0: raise ValueError(f'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model lowerCamelCase__ : Optional[Any] = MusicgenForConditionalGeneration(text_encoder=UpperCamelCase , audio_encoder=UpperCamelCase , decoder=UpperCamelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(UpperCamelCase ) # check we can do a forward pass lowerCamelCase__ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) lowerCamelCase__ : Optional[Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): lowerCamelCase__ : Union[str, Any] = model(input_ids=UpperCamelCase , decoder_input_ids=UpperCamelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor lowerCamelCase__ : str = AutoTokenizer.from_pretrained("""t5-base""" ) lowerCamelCase__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) lowerCamelCase__ : Optional[int] = MusicgenProcessor(feature_extractor=UpperCamelCase , tokenizer=UpperCamelCase ) # set the appropriate bos/pad token ids lowerCamelCase__ : Union[str, Any] = 2048 lowerCamelCase__ : List[str] = 2048 # set other default generation config params lowerCamelCase__ : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[Any] = 3.0 if pytorch_dump_folder is not None: Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) logger.info(f'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) if repo_id: logger.info(f'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(UpperCamelCase ) processor.push_to_hub(UpperCamelCase ) if __name__ == "__main__": _A : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) _A : List[str] =parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
41
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowerCAmelCase : Dict = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Union[str, Any] = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowerCAmelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure)
308
def UpperCamelCase_( _snake_case : str , _snake_case : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(_snake_case ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
308
1