code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""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 _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''google/mobilenet_v2_1.4_224''': '''https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json''', '''google/mobilenet_v2_1.0_224''': '''https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json''', '''google/mobilenet_v2_0.75_160''': '''https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json''', '''google/mobilenet_v2_0.35_96''': '''https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json''', # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''mobilenet_v2''' def __init__( self :Any , _lowerCamelCase :List[str]=3 , _lowerCamelCase :Tuple=2_2_4 , _lowerCamelCase :List[Any]=1.0 , _lowerCamelCase :List[Any]=8 , _lowerCamelCase :Tuple=8 , _lowerCamelCase :Optional[Any]=6 , _lowerCamelCase :Dict=3_2 , _lowerCamelCase :Dict=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :List[str]="relu6" , _lowerCamelCase :Any=True , _lowerCamelCase :Any=0.8 , _lowerCamelCase :List[str]=0.0_2 , _lowerCamelCase :Any=0.0_0_1 , _lowerCamelCase :Union[str, Any]=2_5_5 , **_lowerCamelCase :str , ): super().__init__(**_lowerCamelCase ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) __SCREAMING_SNAKE_CASE : List[str] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = image_size __SCREAMING_SNAKE_CASE : Optional[Any] = depth_multiplier __SCREAMING_SNAKE_CASE : Tuple = depth_divisible_by __SCREAMING_SNAKE_CASE : List[Any] = min_depth __SCREAMING_SNAKE_CASE : Any = expand_ratio __SCREAMING_SNAKE_CASE : str = output_stride __SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion __SCREAMING_SNAKE_CASE : List[str] = finegrained_output __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : int = tf_padding __SCREAMING_SNAKE_CASE : List[str] = classifier_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range __SCREAMING_SNAKE_CASE : List[Any] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = semantic_loss_ignore_index class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def SCREAMING_SNAKE_CASE_ ( self :Any ): if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return 1e-4
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" import os def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = os.path.dirname(os.path.realpath(lowercase_ ) ) __SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(lowercase_ , '''triangle.txt''' ) with open(lowercase_ ) as f: __SCREAMING_SNAKE_CASE : Dict = f.readlines() __SCREAMING_SNAKE_CASE : Optional[int] = [] for line in triangle: __SCREAMING_SNAKE_CASE : Union[str, Any] = [] for number in line.strip().split(''' ''' ): numbers_from_line.append(int(lowercase_ ) ) a.append(lowercase_ ) for i in range(1 , len(lowercase_ ) ): for j in range(len(a[i] ) ): __SCREAMING_SNAKE_CASE : Optional[int] = a[i - 1][j] if j != len(a[i - 1] ) else 0 __SCREAMING_SNAKE_CASE : Optional[Any] = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(lowercase_ , lowercase_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :int=2 , _lowerCamelCase :Tuple=8 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :List[str]=True , _lowerCamelCase :Union[str, Any]=9_9 , _lowerCamelCase :int=1_6 , _lowerCamelCase :str=5 , _lowerCamelCase :List[Any]=2 , _lowerCamelCase :int=3_6 , _lowerCamelCase :Optional[Any]="gelu" , _lowerCamelCase :int=0.0 , _lowerCamelCase :Union[str, Any]=0.0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Any=1_6 , _lowerCamelCase :Any=2 , _lowerCamelCase :Union[str, Any]=0.0_2 , _lowerCamelCase :Union[str, Any]=3 , _lowerCamelCase :Tuple=4 , _lowerCamelCase :Dict=None , ): __SCREAMING_SNAKE_CASE : Optional[Any] = parent __SCREAMING_SNAKE_CASE : Optional[Any] = batch_size __SCREAMING_SNAKE_CASE : Dict = seq_length __SCREAMING_SNAKE_CASE : Tuple = is_training __SCREAMING_SNAKE_CASE : List[str] = use_input_mask __SCREAMING_SNAKE_CASE : Union[str, Any] = use_token_type_ids __SCREAMING_SNAKE_CASE : Optional[int] = use_labels __SCREAMING_SNAKE_CASE : Any = vocab_size __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size __SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : int = type_vocab_size __SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : List[str] = initializer_range __SCREAMING_SNAKE_CASE : Tuple = num_labels __SCREAMING_SNAKE_CASE : List[str] = num_choices __SCREAMING_SNAKE_CASE : List[str] = scope def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : int = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : List[Any] = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self :int ): return MraConfig( 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=_lowerCamelCase , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Any = self.get_config() __SCREAMING_SNAKE_CASE : str = 3_0_0 return config def SCREAMING_SNAKE_CASE_ ( self :List[str] ): ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) : List[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = True __SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Any = MraModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[Any] , _lowerCamelCase :int , _lowerCamelCase :List[Any] , _lowerCamelCase :Any , _lowerCamelCase :List[str] , _lowerCamelCase :int , _lowerCamelCase :Optional[int] , _lowerCamelCase :Any , _lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Optional[Any] = MraModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :Tuple , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = MraForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Any , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : str = MraForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , start_positions=_lowerCamelCase , end_positions=_lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :str , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels __SCREAMING_SNAKE_CASE : Optional[Any] = MraForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :List[str] , _lowerCamelCase :str , _lowerCamelCase :List[Any] , _lowerCamelCase :Any , _lowerCamelCase :Any , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : List[Any] = self.num_labels __SCREAMING_SNAKE_CASE : Optional[Any] = MraForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[str] , _lowerCamelCase :str , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Any , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : List[Any] = self.num_choices __SCREAMING_SNAKE_CASE : int = MraForMultipleChoice(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) : List[str] = config_and_inputs __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = () def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : str = MraModelTester(self ) __SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( self :Any ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE : str = type self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[Any] = MraModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skip(reason='''MRA does not output attentions''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return @require_torch class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __SCREAMING_SNAKE_CASE : str = torch.arange(2_5_6 ).unsqueeze(0 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : List[Any] = torch.Size((1, 2_5_6, 7_6_8) ) self.assertEqual(output.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __SCREAMING_SNAKE_CASE : str = torch.arange(2_5_6 ).unsqueeze(0 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Optional[int] = 5_0_2_6_5 __SCREAMING_SNAKE_CASE : str = torch.Size((1, 2_5_6, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Dict = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __SCREAMING_SNAKE_CASE : Any = torch.arange(4_0_9_6 ).unsqueeze(0 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : str = 5_0_2_6_5 __SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 4_0_9_6, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) __SCREAMING_SNAKE_CASE : Optional[int] = hex_num[0] == '''-''' if is_negative: __SCREAMING_SNAKE_CASE : Optional[int] = hex_num[1:] try: __SCREAMING_SNAKE_CASE : Union[str, Any] = int(lowercase_ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) __SCREAMING_SNAKE_CASE : List[str] = '''''' while int_num > 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from pathlib import Path import fire from tqdm import tqdm def lowerCAmelCase_ ( lowercase_ : List[Any]="ro" , lowercase_ : Dict="en" , lowercase_ : Optional[Any]="wmt16" , lowercase_ : List[Any]=None ): '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('''run pip install datasets''' ) __SCREAMING_SNAKE_CASE : int = F'''{src_lang}-{tgt_lang}''' print(F'''Converting {dataset}-{pair}''' ) __SCREAMING_SNAKE_CASE : str = datasets.load_dataset(lowercase_ , lowercase_ ) if save_dir is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = F'''{dataset}-{pair}''' __SCREAMING_SNAKE_CASE : int = Path(lowercase_ ) save_dir.mkdir(exist_ok=lowercase_ ) for split in ds.keys(): print(F'''Splitting {split} with {ds[split].num_rows} records''' ) # to save to val.source, val.target like summary datasets __SCREAMING_SNAKE_CASE : Optional[int] = '''val''' if split == '''validation''' else split __SCREAMING_SNAKE_CASE : Any = save_dir.joinpath(F'''{fn}.source''' ) __SCREAMING_SNAKE_CASE : Any = save_dir.joinpath(F'''{fn}.target''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = src_path.open('''w+''' ) __SCREAMING_SNAKE_CASE : int = tgt_path.open('''w+''' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): __SCREAMING_SNAKE_CASE : Optional[int] = x['''translation'''] src_fp.write(ex[src_lang] + '''\n''' ) tgt_fp.write(ex[tgt_lang] + '''\n''' ) print(F'''Saved {dataset} dataset to {save_dir}''' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class snake_case ( metaclass=__UpperCAmelCase ): lowerCamelCase__ = ['''torch''', '''scipy'''] def __init__( self :Optional[int] , *_lowerCamelCase :Tuple , **_lowerCamelCase :int ): requires_backends(self , ['''torch''', '''scipy'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :int , *_lowerCamelCase :Optional[int] , **_lowerCamelCase :int ): requires_backends(cls , ['''torch''', '''scipy'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Any , *_lowerCamelCase :Optional[Any] , **_lowerCamelCase :Optional[int] ): requires_backends(cls , ['''torch''', '''scipy'''] )
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 50 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = XGLMTokenizer lowerCamelCase__ = XGLMTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : List[str] = XGLMTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Dict = '''<pad>''' __SCREAMING_SNAKE_CASE : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(_lowerCamelCase ) , 1_0_0_8 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = XGLMTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = 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 [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def SCREAMING_SNAKE_CASE_ ( self :str ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(_lowerCamelCase , f.name ) __SCREAMING_SNAKE_CASE : Optional[int] = XGLMTokenizer(f.name , keep_accents=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = pickle.dumps(_lowerCamelCase ) pickle.loads(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : str = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : str = tokenizer.tokenize(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = rust_tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : int = tokenizer.encode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.encode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : str = '''Hello World!''' __SCREAMING_SNAKE_CASE : Union[str, Any] = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off __SCREAMING_SNAKE_CASE : Any = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # fmt: off __SCREAMING_SNAKE_CASE : str = { '''input_ids''': [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], '''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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''facebook/xglm-564M''' , padding=_lowerCamelCase , )
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''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 snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ['''pixel_values'''] def __init__( self :int , _lowerCamelCase :bool = True , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :PILImageResampling = PILImageResampling.BILINEAR , _lowerCamelCase :bool = True , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :bool = True , _lowerCamelCase :Union[int, float] = 1 / 2_5_5 , _lowerCamelCase :bool = True , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , **_lowerCamelCase :List[Any] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {'''shortest_edge''': 2_2_4} __SCREAMING_SNAKE_CASE : Any = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} __SCREAMING_SNAKE_CASE : str = get_size_dict(_lowerCamelCase , param_name='''crop_size''' ) __SCREAMING_SNAKE_CASE : str = do_resize __SCREAMING_SNAKE_CASE : str = size __SCREAMING_SNAKE_CASE : Dict = do_center_crop __SCREAMING_SNAKE_CASE : Tuple = crop_size __SCREAMING_SNAKE_CASE : Dict = resample __SCREAMING_SNAKE_CASE : Any = do_rescale __SCREAMING_SNAKE_CASE : Tuple = rescale_factor __SCREAMING_SNAKE_CASE : Optional[Any] = do_normalize __SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Dict[str, int] , _lowerCamelCase :PILImageResampling = PILImageResampling.BILINEAR , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Optional[int] , ): __SCREAMING_SNAKE_CASE : Dict = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) if "shortest_edge" in size: __SCREAMING_SNAKE_CASE : Dict = get_resize_output_image_size(_lowerCamelCase , size['''shortest_edge'''] , default_to_square=_lowerCamelCase ) elif "height" in size and "width" in size: __SCREAMING_SNAKE_CASE : Tuple = (size['''height'''], size['''width''']) else: raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Dict[str, int] , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Union[str, Any] , ): __SCREAMING_SNAKE_CASE : Optional[Any] = get_size_dict(_lowerCamelCase ) 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(_lowerCamelCase , size=(size['''height'''], size['''width''']) , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :np.ndarray , _lowerCamelCase :Union[int, float] , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Dict , ): return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Union[float, List[float]] , _lowerCamelCase :Union[float, List[float]] , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :int , ): return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :ImageInput , _lowerCamelCase :bool = None , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :PILImageResampling = None , _lowerCamelCase :bool = None , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :bool = None , _lowerCamelCase :float = None , _lowerCamelCase :bool = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :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.''' ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE : Dict = to_numpy_array(_lowerCamelCase ) if do_resize: __SCREAMING_SNAKE_CASE : Tuple = self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) if do_center_crop: __SCREAMING_SNAKE_CASE : str = self.center_crop(_lowerCamelCase , size=_lowerCamelCase ) if do_rescale: __SCREAMING_SNAKE_CASE : List[Any] = self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) if do_normalize: __SCREAMING_SNAKE_CASE : List[str] = self.normalize(image=_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) return image def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :ImageInput , _lowerCamelCase :bool = None , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :PILImageResampling = None , _lowerCamelCase :bool = None , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :bool = None , _lowerCamelCase :float = None , _lowerCamelCase :bool = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[str, TensorType]] = None , _lowerCamelCase :ChannelDimension = ChannelDimension.FIRST , **_lowerCamelCase :Union[str, Any] , ): __SCREAMING_SNAKE_CASE : int = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE : Dict = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE : List[str] = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE : Any = size if size is not None else self.size __SCREAMING_SNAKE_CASE : Optional[Any] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = crop_size if crop_size is not None else self.crop_size __SCREAMING_SNAKE_CASE : Dict = get_size_dict(_lowerCamelCase , param_name='''crop_size''' ) if not valid_images(_lowerCamelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) __SCREAMING_SNAKE_CASE : str = make_batched(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = [ [ self._preprocess_image( image=_lowerCamelCase , do_resize=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , do_center_crop=_lowerCamelCase , crop_size=_lowerCamelCase , do_rescale=_lowerCamelCase , rescale_factor=_lowerCamelCase , do_normalize=_lowerCamelCase , image_mean=_lowerCamelCase , image_std=_lowerCamelCase , data_format=_lowerCamelCase , ) for img in video ] for video in videos ] __SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': videos} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py _lowerCamelCase = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. _lowerCamelCase = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) _lowerCamelCase = spec.loader.load_module() _lowerCamelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` _lowerCamelCase = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') _lowerCamelCase = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = [] for config_class in list(CONFIG_MAPPING.values() ): __SCREAMING_SNAKE_CASE : Optional[Any] = False # source code of `config_class` __SCREAMING_SNAKE_CASE : Any = inspect.getsource(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = _re_checkpoint.findall(lowercase_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = checkpoint # verify the checkpoint name corresponds to the checkpoint link __SCREAMING_SNAKE_CASE : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: __SCREAMING_SNAKE_CASE : Any = True break __SCREAMING_SNAKE_CASE : Optional[Any] = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(lowercase_ ) if len(lowercase_ ) > 0: __SCREAMING_SNAKE_CASE : Optional[int] = '''\n'''.join(sorted(lowercase_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = OmegaConf.load(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = torch.load(lowercase_ , map_location='''cpu''' )['''model'''] __SCREAMING_SNAKE_CASE : List[str] = list(state_dict.keys() ) # extract state_dict for VQVAE __SCREAMING_SNAKE_CASE : Union[str, Any] = {} __SCREAMING_SNAKE_CASE : List[Any] = '''first_stage_model.''' for key in keys: if key.startswith(lowercase_ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict[key] # extract state_dict for UNetLDM __SCREAMING_SNAKE_CASE : List[Any] = {} __SCREAMING_SNAKE_CASE : List[str] = '''model.diffusion_model.''' for key in keys: if key.startswith(lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[int] = state_dict[key] __SCREAMING_SNAKE_CASE : Dict = config.model.params.first_stage_config.params __SCREAMING_SNAKE_CASE : Union[str, Any] = config.model.params.unet_config.params __SCREAMING_SNAKE_CASE : Optional[Any] = VQModel(**lowercase_ ).eval() vqvae.load_state_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = UNetLDMModel(**lowercase_ ).eval() unet.load_state_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule='''scaled_linear''' , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=lowercase_ , ) __SCREAMING_SNAKE_CASE : Tuple = LDMPipeline(lowercase_ , lowercase_ , lowercase_ ) pipeline.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', type=str, required=True) parser.add_argument('''--config_path''', type=str, required=True) parser.add_argument('''--output_path''', type=str, required=True) _lowerCamelCase = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = '''''' for i in table: res += inp[i - 1] return res def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return data[1:] + data[0] def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = '''''' for i in range(len(lowercase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = int('''0b''' + data[0] + data[-1] , 2 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int('''0b''' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Optional[Any] , lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = message[:4] __SCREAMING_SNAKE_CASE : Any = message[4:] __SCREAMING_SNAKE_CASE : int = apply_table(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : str = xor(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = apply_sbox(lowercase_ , temp[:4] ) # noqa: E741 __SCREAMING_SNAKE_CASE : Tuple = apply_sbox(lowercase_ , temp[4:] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''0''' * (2 - len(lowercase_ )) + l # noqa: E741 __SCREAMING_SNAKE_CASE : Tuple = '''0''' * (2 - len(lowercase_ )) + r __SCREAMING_SNAKE_CASE : Any = apply_table(l + r , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = xor(lowercase_ , lowercase_ ) return temp + right if __name__ == "__main__": _lowerCamelCase = input('''Enter 10 bit key: ''') _lowerCamelCase = input('''Enter 8 bit message: ''') _lowerCamelCase = [6, 3, 7, 4, 8, 5, 10, 9] _lowerCamelCase = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] _lowerCamelCase = [2, 4, 3, 1] _lowerCamelCase = [2, 6, 3, 1, 4, 8, 5, 7] _lowerCamelCase = [4, 1, 3, 5, 7, 2, 8, 6] _lowerCamelCase = [4, 1, 2, 3, 2, 3, 4, 1] _lowerCamelCase = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] _lowerCamelCase = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation _lowerCamelCase = apply_table(key, paa_table) _lowerCamelCase = temp[:5] _lowerCamelCase = temp[5:] _lowerCamelCase = left_shift(left) _lowerCamelCase = left_shift(right) _lowerCamelCase = apply_table(left + right, pa_table) _lowerCamelCase = left_shift(left) _lowerCamelCase = left_shift(right) _lowerCamelCase = left_shift(left) _lowerCamelCase = left_shift(right) _lowerCamelCase = apply_table(left + right, pa_table) # encryption _lowerCamelCase = apply_table(message, IP) _lowerCamelCase = function(expansion, sa, sa, keya, temp) _lowerCamelCase = temp[4:] + temp[:4] _lowerCamelCase = function(expansion, sa, sa, keya, temp) _lowerCamelCase = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption _lowerCamelCase = apply_table(CT, IP) _lowerCamelCase = function(expansion, sa, sa, keya, temp) _lowerCamelCase = temp[4:] + temp[:4] _lowerCamelCase = function(expansion, sa, sa, keya, temp) _lowerCamelCase = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" import os def lowerCAmelCase_ ( lowercase_ : str = "input.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) as input_file: __SCREAMING_SNAKE_CASE : Tuple = [ [int(lowercase_ ) for element in line.split(''',''' )] for line in input_file.readlines() ] __SCREAMING_SNAKE_CASE : Union[str, Any] = len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = len(matrix[0] ) __SCREAMING_SNAKE_CASE : Any = [[-1 for _ in range(lowercase_ )] for _ in range(lowercase_ )] for i in range(lowercase_ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = matrix[i][0] for j in range(1 , lowercase_ ): for i in range(lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[Any] = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): __SCREAMING_SNAKE_CASE : Optional[int] = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 400_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = b, a + b return sum(lowercase_ ) if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' return x + 2 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = '''x = 3''' __SCREAMING_SNAKE_CASE : Tuple = {} __SCREAMING_SNAKE_CASE : Optional[int] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) assert result == 3 self.assertDictEqual(_lowerCamelCase , {'''x''': 3} ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''x = y''' __SCREAMING_SNAKE_CASE : List[Any] = {'''y''': 5} __SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 5, '''y''': 5} ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = '''y = add_two(x)''' __SCREAMING_SNAKE_CASE : List[Any] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(_lowerCamelCase , {'''add_two''': add_two} , state=_lowerCamelCase ) assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''y''': 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE : List[str] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) assert result is None assert "tried to execute add_two" in out.out def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = '''x = 3''' __SCREAMING_SNAKE_CASE : List[str] = {} __SCREAMING_SNAKE_CASE : List[Any] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) assert result == 3 self.assertDictEqual(_lowerCamelCase , {'''x''': 3} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : int = '''test_dict = {\'x\': x, \'y\': add_two(x)}''' __SCREAMING_SNAKE_CASE : List[str] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(_lowerCamelCase , {'''add_two''': add_two} , state=_lowerCamelCase ) self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''y''': 5} ) self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Any = '''x = 3\ny = 5''' __SCREAMING_SNAKE_CASE : int = {} __SCREAMING_SNAKE_CASE : str = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''y''': 5} ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[int] = '''text = f\'This is x: {x}.\'''' __SCREAMING_SNAKE_CASE : Optional[Any] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Any = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''text''': '''This is x: 3.'''} ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''if x <= 3:\n y = 2\nelse:\n y = 5''' __SCREAMING_SNAKE_CASE : int = {'''x''': 3} __SCREAMING_SNAKE_CASE : List[Any] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''y''': 2} ) __SCREAMING_SNAKE_CASE : List[Any] = {'''x''': 8} __SCREAMING_SNAKE_CASE : int = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 8, '''y''': 5} ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : int = '''test_list = [x, add_two(x)]''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(_lowerCamelCase , {'''add_two''': add_two} , state=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , [3, 5] ) self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''test_list''': [3, 5]} ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''y = x''' __SCREAMING_SNAKE_CASE : Optional[Any] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Optional[int] = evaluate(_lowerCamelCase , {} , state=_lowerCamelCase ) assert result == 3 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''y''': 3} ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[Any] = '''test_list = [x, add_two(x)]\ntest_list[1]''' __SCREAMING_SNAKE_CASE : List[str] = {'''x''': 3} __SCREAMING_SNAKE_CASE : Optional[int] = evaluate(_lowerCamelCase , {'''add_two''': add_two} , state=_lowerCamelCase ) assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''test_list''': [3, 5]} ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']''' __SCREAMING_SNAKE_CASE : Dict = {'''x''': 3} __SCREAMING_SNAKE_CASE : int = evaluate(_lowerCamelCase , {'''add_two''': add_two} , state=_lowerCamelCase ) assert result == 5 self.assertDictEqual(_lowerCamelCase , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Any = '''x = 0\nfor i in range(3):\n x = i''' __SCREAMING_SNAKE_CASE : Tuple = {} __SCREAMING_SNAKE_CASE : str = evaluate(_lowerCamelCase , {'''range''': range} , state=_lowerCamelCase ) assert result == 2 self.assertDictEqual(_lowerCamelCase , {'''x''': 2, '''i''': 2} )
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu _lowerCamelCase = get_tests_dir() + '''/test_data/fsmt/fsmt_val_data.json''' with io.open(filename, '''r''', encoding='''utf-8''') as f: _lowerCamelCase = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict ): return FSMTTokenizer.from_pretrained(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Tuple = FSMTForConditionalGeneration.from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['''en-ru''', 2_6.0], ['''ru-en''', 2_2.0], ['''en-de''', 2_2.0], ['''de-en''', 2_9.0], ] ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Any , _lowerCamelCase :Dict ): # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality __SCREAMING_SNAKE_CASE : Dict = f'''facebook/wmt19-{pair}''' __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.get_model(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = bleu_data[pair]['''src'''] __SCREAMING_SNAKE_CASE : int = bleu_data[pair]['''tgt'''] __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(_lowerCamelCase , return_tensors='''pt''' , truncation=_lowerCamelCase , padding='''longest''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.generate( input_ids=batch.input_ids , num_beams=8 , ) __SCREAMING_SNAKE_CASE : Any = tokenizer.batch_decode( _lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = calculate_bleu(_lowerCamelCase , _lowerCamelCase ) print(_lowerCamelCase ) self.assertGreaterEqual(scores['''bleu'''] , _lowerCamelCase )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" from __future__ import annotations _lowerCamelCase = 8.988e9 # units = N * m^s * C^-2 def lowerCAmelCase_ ( lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if distance < 0: raise ValueError('''Distance cannot be negative''' ) if force == 0: __SCREAMING_SNAKE_CASE : str = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: __SCREAMING_SNAKE_CASE : Optional[Any] = abs(lowercase_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: __SCREAMING_SNAKE_CASE : Dict = abs(lowercase_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: __SCREAMING_SNAKE_CASE : int = (COULOMBS_CONSTANT * charge_product / abs(lowercase_ )) ** 0.5 return {"distance": distance} raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" 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 lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = 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''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : def __init__( self :str , _lowerCamelCase :Tuple=2 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Tuple=6_4 , _lowerCamelCase :List[Any]=None ): __SCREAMING_SNAKE_CASE : Optional[Any] = np.random.default_rng(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = length __SCREAMING_SNAKE_CASE : Optional[Any] = rng.normal(size=(length,) ).astype(np.floataa ) __SCREAMING_SNAKE_CASE : Optional[Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self :Optional[int] ): return self.length def __getitem__( self :Tuple , _lowerCamelCase :Any ): return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): def __init__( self :int , _lowerCamelCase :Optional[Any]=0 , _lowerCamelCase :Union[str, Any]=0 , _lowerCamelCase :Dict=False ): super().__init__() __SCREAMING_SNAKE_CASE : str = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __SCREAMING_SNAKE_CASE : Optional[int] = True def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int]=None ): if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) __SCREAMING_SNAKE_CASE : List[Any] = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): def __init__( self :int , _lowerCamelCase :int=0 , _lowerCamelCase :Any=0 , _lowerCamelCase :int=False ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __SCREAMING_SNAKE_CASE : str = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __SCREAMING_SNAKE_CASE : Tuple = True def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :List[str]=None ): if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) __SCREAMING_SNAKE_CASE : List[str] = False return x * self.a + self.b def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : int = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer __SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __SCREAMING_SNAKE_CASE : List[Any] = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __SCREAMING_SNAKE_CASE : int = load_dataset('''csv''' , data_files=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = datasets['''train'''].unique('''label''' ) __SCREAMING_SNAKE_CASE : int = {v: i for i, v in enumerate(lowercase_ )} def tokenize_function(lowercase_ : List[str] ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowercase_ , max_length=lowercase_ , padding='''max_length''' ) if "label" in examples: __SCREAMING_SNAKE_CASE : Union[str, Any] = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __SCREAMING_SNAKE_CASE : Optional[Any] = datasets.map( lowercase_ , batched=lowercase_ , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(lowercase_ : Tuple ): # 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. __SCREAMING_SNAKE_CASE : List[Any] = DataLoader(tokenized_datasets['''train'''] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=2 ) __SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader(tokenized_datasets['''validation'''] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=1 ) return train_dataloader, eval_dataloader
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = (IPNDMScheduler,) lowerCamelCase__ = (('''num_inference_steps''', 50),) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , **_lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''num_train_timesteps''': 1_0_0_0} config.update(**_lowerCamelCase ) return config def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[Any]=0 , **_lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : int = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''num_inference_steps''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_sample __SCREAMING_SNAKE_CASE : Optional[int] = 0.1 * sample __SCREAMING_SNAKE_CASE : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE : List[str] = self.get_scheduler_config(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = scheduler_class(**_lowerCamelCase ) scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals __SCREAMING_SNAKE_CASE : Union[str, Any] = dummy_past_residuals[:] if time_step is None: __SCREAMING_SNAKE_CASE : Tuple = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = scheduler_class.from_pretrained(_lowerCamelCase ) new_scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals __SCREAMING_SNAKE_CASE : Any = dummy_past_residuals[:] __SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Optional[Any] = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __SCREAMING_SNAKE_CASE : Any = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Tuple = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Any=0 , **_lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE : Any = kwargs.pop('''num_inference_steps''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.dummy_sample __SCREAMING_SNAKE_CASE : List[Any] = 0.1 * sample __SCREAMING_SNAKE_CASE : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE : Dict = self.get_scheduler_config() __SCREAMING_SNAKE_CASE : int = scheduler_class(**_lowerCamelCase ) scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals (must be after setting timesteps) __SCREAMING_SNAKE_CASE : Any = dummy_past_residuals[:] if time_step is None: __SCREAMING_SNAKE_CASE : str = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = scheduler_class.from_pretrained(_lowerCamelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residual (must be after setting timesteps) __SCREAMING_SNAKE_CASE : Any = dummy_past_residuals[:] __SCREAMING_SNAKE_CASE : Union[str, Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Union[str, Any] = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __SCREAMING_SNAKE_CASE : int = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Dict = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE_ ( self :Dict , **_lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE : Optional[int] = self.get_scheduler_config(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = scheduler_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 1_0 __SCREAMING_SNAKE_CASE : Any = self.dummy_model() __SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(_lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample return sample def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[int] = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE : int = kwargs.pop('''num_inference_steps''' , _lowerCamelCase ) for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE : List[Any] = self.get_scheduler_config() __SCREAMING_SNAKE_CASE : str = scheduler_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.dummy_sample __SCREAMING_SNAKE_CASE : Dict = 0.1 * sample if num_inference_steps is not None and hasattr(_lowerCamelCase , '''set_timesteps''' ): scheduler.set_timesteps(_lowerCamelCase ) elif num_inference_steps is not None and not hasattr(_lowerCamelCase , '''set_timesteps''' ): __SCREAMING_SNAKE_CASE : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __SCREAMING_SNAKE_CASE : List[str] = [residual + 0.2, residual + 0.1_5, residual + 0.1, residual + 0.0_5] __SCREAMING_SNAKE_CASE : Dict = dummy_past_residuals[:] __SCREAMING_SNAKE_CASE : Any = scheduler.timesteps[5] __SCREAMING_SNAKE_CASE : Optional[int] = scheduler.timesteps[6] __SCREAMING_SNAKE_CASE : List[str] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Dict = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __SCREAMING_SNAKE_CASE : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __SCREAMING_SNAKE_CASE : Dict = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): for timesteps in [1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_lowerCamelCase , time_step=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): for t, num_inference_steps in zip([1, 5, 1_0] , [1_0, 5_0, 1_0_0] ): self.check_over_forward(num_inference_steps=_lowerCamelCase , time_step=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = self.full_loop() __SCREAMING_SNAKE_CASE : Dict = torch.mean(torch.abs(_lowerCamelCase ) ) assert abs(result_mean.item() - 2_5_4_0_5_2_9 ) < 1_0
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowerCamelCase = WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = test_results.split(''' ''' ) __SCREAMING_SNAKE_CASE : Any = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __SCREAMING_SNAKE_CASE : Union[str, Any] = expressions[-2] if '''=''' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase_ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = {} __SCREAMING_SNAKE_CASE : Tuple = None __SCREAMING_SNAKE_CASE : str = False for line in failures_short_lines.split('''\n''' ): if re.search(r'''_ \[doctest\]''' , lowercase_ ): __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : str = line.split(''' ''' )[2] elif in_error and not line.split(''' ''' )[0].isdigit(): __SCREAMING_SNAKE_CASE : List[str] = line __SCREAMING_SNAKE_CASE : List[Any] = False return failures class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = title __SCREAMING_SNAKE_CASE : Union[str, Any] = doc_test_results['''time_spent'''].split(''',''' )[0] __SCREAMING_SNAKE_CASE : Dict = doc_test_results['''success'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = doc_test_results['''failures'''] __SCREAMING_SNAKE_CASE : Optional[int] = self.n_success + self.n_failures # Failures and success of the modeling tests __SCREAMING_SNAKE_CASE : List[str] = doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[str] = [self._time_spent] __SCREAMING_SNAKE_CASE : Any = 0 for time in time_spent: __SCREAMING_SNAKE_CASE : int = time.split(''':''' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(_lowerCamelCase ) == 1: __SCREAMING_SNAKE_CASE : str = [0, 0, time_parts[0]] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3_6_0_0 + minutes * 6_0 + seconds __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = total_secs // 3_6_0_0, (total_secs % 3_6_0_0) // 6_0, total_secs % 6_0 return f'''{int(_lowerCamelCase )}h{int(_lowerCamelCase )}m{int(_lowerCamelCase )}s''' @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self :int ): return { "type": "section", "text": { "type": "plain_text", "text": f'''🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.''', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'''There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in''' f''' {self.time}.''' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 4_0 __SCREAMING_SNAKE_CASE : Union[str, Any] = {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(_lowerCamelCase , _lowerCamelCase )} __SCREAMING_SNAKE_CASE : Tuple = '''''' for category, failures in category_failures.items(): if len(_lowerCamelCase ) == 0: continue if report != "": report += "\n\n" report += f'''*{category} failures*:'''.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(_lowerCamelCase ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'''The following examples had failures:\n\n\n{report}\n''', }, } @property def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ): __SCREAMING_SNAKE_CASE : List[Any] = [ { '''type''': '''section''', '''text''': { '''type''': '''plain_text''', '''text''': '''There was an issue running the tests.''', }, '''accessory''': { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True}, '''url''': f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } ] print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(_lowerCamelCase )} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text='''There was an issue running the tests.''' , blocks=_lowerCamelCase , ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(self.payload )} ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = f'''{self.n_failures} failures out of {self.n_tests} tests,''' if self.n_failures else '''All tests passed.''' __SCREAMING_SNAKE_CASE : int = client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , blocks=self.payload , text=_lowerCamelCase , ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[str] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = '''''' for key, value in failures.items(): __SCREAMING_SNAKE_CASE : int = value[:2_0_0] + ''' [Truncated]''' if len(_lowerCamelCase ) > 2_5_0 else value failures_text += f'''*{key}*\n_{value}_\n\n''' __SCREAMING_SNAKE_CASE : Optional[Any] = job_name __SCREAMING_SNAKE_CASE : Optional[int] = {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}} if job_link is not None: __SCREAMING_SNAKE_CASE : Optional[int] = { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''GitHub Action job''', '''emoji''': True}, '''url''': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self :Dict ): if self.thread_ts is None: raise ValueError('''Can only post reply if a post has been made.''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.doc_test_results.pop('''job_link''' ) self.doc_test_results.pop('''failures''' ) self.doc_test_results.pop('''success''' ) self.doc_test_results.pop('''time_spent''' ) __SCREAMING_SNAKE_CASE : Any = sorted(self.doc_test_results.items() , key=lambda _lowerCamelCase : t[0] ) for job, job_result in sorted_dict: if len(job_result['''failures'''] ): __SCREAMING_SNAKE_CASE : Dict = f'''*Num failures* :{len(job_result['failed'] )} \n''' __SCREAMING_SNAKE_CASE : Union[str, Any] = job_result['''failures'''] __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_reply_blocks(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , text=_lowerCamelCase ) print('''Sending the following reply''' ) print(json.dumps({'''blocks''': blocks} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text=f'''Results for {job}''' , blocks=_lowerCamelCase , thread_ts=self.thread_ts['''ts'''] , ) time.sleep(1 ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = os.environ['''GITHUB_RUN_ID'''] __SCREAMING_SNAKE_CASE : str = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100''' __SCREAMING_SNAKE_CASE : Union[str, Any] = requests.get(lowercase_ ).json() __SCREAMING_SNAKE_CASE : int = {} try: jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) __SCREAMING_SNAKE_CASE : str = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(lowercase_ ): __SCREAMING_SNAKE_CASE : List[Any] = requests.get(url + F'''&page={i + 2}''' ).json() jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return jobs except Exception as e: print('''Unknown error, could not fetch links.''' , lowercase_ ) return {} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {} if os.path.exists(lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = os.listdir(lowercase_ ) for file in files: try: with open(os.path.join(lowercase_ , lowercase_ ) , encoding='''utf-8''' ) as f: __SCREAMING_SNAKE_CASE : Any = f.read() except UnicodeDecodeError as e: raise ValueError(F'''Could not open {os.path.join(lowercase_ , lowercase_ )}.''' ) from e return _artifact def lowerCAmelCase_ ( ): '''simple docstring''' class snake_case : def __init__( self :Union[str, Any] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Optional[int] = name __SCREAMING_SNAKE_CASE : Dict = [] def __str__( self :Tuple ): return self.name def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :str ): self.paths.append({'''name''': self.name, '''path''': path} ) __SCREAMING_SNAKE_CASE : Dict[str, Artifact] = {} __SCREAMING_SNAKE_CASE : int = filter(os.path.isdir , os.listdir() ) for directory in directories: __SCREAMING_SNAKE_CASE : List[Any] = directory if artifact_name not in _available_artifacts: __SCREAMING_SNAKE_CASE : List[str] = Artifact(lowercase_ ) _available_artifacts[artifact_name].add_path(lowercase_ ) return _available_artifacts if __name__ == "__main__": _lowerCamelCase = get_job_links() _lowerCamelCase = retrieve_available_artifacts() _lowerCamelCase = collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowerCamelCase = { v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowerCamelCase = github_actions_job_links.get('''run_doctests''') _lowerCamelCase = available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowerCamelCase = retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = handle_test_results(artifact['''stats''']) _lowerCamelCase = failed _lowerCamelCase = success _lowerCamelCase = time_spent[1:-1] + ''', ''' _lowerCamelCase = extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowerCamelCase = line.replace('''FAILED ''', '''''') _lowerCamelCase = line.split()[0].replace('''\n''', '''''') if "::" in line: _lowerCamelCase , _lowerCamelCase = line.split('''::''') else: _lowerCamelCase , _lowerCamelCase = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowerCamelCase = docs[file_regex] doc_test_results[category]["failed"].append(test) _lowerCamelCase = all_failures[test] if test in all_failures else '''N/A''' _lowerCamelCase = failure break _lowerCamelCase = Message('''🤗 Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" from collections.abc import Sequence from queue import Queue class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Any=None , _lowerCamelCase :Union[str, Any]=None ): __SCREAMING_SNAKE_CASE : Any = start __SCREAMING_SNAKE_CASE : List[Any] = end __SCREAMING_SNAKE_CASE : str = val __SCREAMING_SNAKE_CASE : str = (start + end) // 2 __SCREAMING_SNAKE_CASE : Any = left __SCREAMING_SNAKE_CASE : Dict = right def __repr__( self :List[Any] ): return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class snake_case : def __init__( self :int , _lowerCamelCase :Sequence , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = collection __SCREAMING_SNAKE_CASE : List[str] = function if self.collection: __SCREAMING_SNAKE_CASE : List[str] = self._build_tree(0 , len(_lowerCamelCase ) - 1 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] , _lowerCamelCase :str ): self._update_tree(self.root , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Tuple , _lowerCamelCase :int ): return self._query_range(self.root , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :List[Any] ): if start == end: return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.collection[start] ) __SCREAMING_SNAKE_CASE : str = (start + end) // 2 __SCREAMING_SNAKE_CASE : str = self._build_tree(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self._build_tree(mid + 1 , _lowerCamelCase ) return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.fn(left.val , right.val ) , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Dict , _lowerCamelCase :Dict , _lowerCamelCase :Optional[Any] ): if node.start == i and node.end == i: __SCREAMING_SNAKE_CASE : Any = val return if i <= node.mid: self._update_tree(node.left , _lowerCamelCase , _lowerCamelCase ) else: self._update_tree(node.right , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.fn(node.left.val , node.right.val ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Union[str, Any] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[Any] ): if self.root is not None: __SCREAMING_SNAKE_CASE : Any = Queue() queue.put(self.root ) while not queue.empty(): __SCREAMING_SNAKE_CASE : Dict = 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) _lowerCamelCase = 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()
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 class snake_case ( nn.Module ): def __init__( self :List[str] , _lowerCamelCase :List[Any]=3 , _lowerCamelCase :Tuple=3 , _lowerCamelCase :List[Any]=("DownEncoderBlock2D",) , _lowerCamelCase :Any=(6_4,) , _lowerCamelCase :Tuple=2 , _lowerCamelCase :Any=3_2 , _lowerCamelCase :Optional[Any]="silu" , _lowerCamelCase :Any=True , ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = layers_per_block __SCREAMING_SNAKE_CASE : Tuple = torch.nn.Convad( _lowerCamelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : str = nn.ModuleList([] ) # down __SCREAMING_SNAKE_CASE : Tuple = block_out_channels[0] for i, down_block_type in enumerate(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = output_channel __SCREAMING_SNAKE_CASE : List[Any] = block_out_channels[i] __SCREAMING_SNAKE_CASE : List[Any] = i == len(_lowerCamelCase ) - 1 __SCREAMING_SNAKE_CASE : int = get_down_block( _lowerCamelCase , num_layers=self.layers_per_block , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=_lowerCamelCase , resnet_groups=_lowerCamelCase , attention_head_dim=_lowerCamelCase , temb_channels=_lowerCamelCase , ) self.down_blocks.append(_lowerCamelCase ) # mid __SCREAMING_SNAKE_CASE : Optional[int] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=_lowerCamelCase , output_scale_factor=1 , resnet_time_scale_shift='''default''' , attention_head_dim=block_out_channels[-1] , resnet_groups=_lowerCamelCase , temb_channels=_lowerCamelCase , ) # out __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=_lowerCamelCase , eps=1e-6 ) __SCREAMING_SNAKE_CASE : Dict = nn.SiLU() __SCREAMING_SNAKE_CASE : Union[str, Any] = 2 * out_channels if double_z else out_channels __SCREAMING_SNAKE_CASE : Tuple = nn.Convad(block_out_channels[-1] , _lowerCamelCase , 3 , padding=1 ) __SCREAMING_SNAKE_CASE : Tuple = False def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = x __SCREAMING_SNAKE_CASE : Tuple = self.conv_in(_lowerCamelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(_lowerCamelCase :Any ): def custom_forward(*_lowerCamelCase :List[Any] ): return module(*_lowerCamelCase ) return custom_forward # down if is_torch_version('''>=''' , '''1.11.0''' ): for down_block in self.down_blocks: __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , use_reentrant=_lowerCamelCase ) # middle __SCREAMING_SNAKE_CASE : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , use_reentrant=_lowerCamelCase ) else: for down_block in self.down_blocks: __SCREAMING_SNAKE_CASE : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCamelCase ) , _lowerCamelCase ) # middle __SCREAMING_SNAKE_CASE : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , _lowerCamelCase ) else: # down for down_block in self.down_blocks: __SCREAMING_SNAKE_CASE : Union[str, Any] = down_block(_lowerCamelCase ) # middle __SCREAMING_SNAKE_CASE : Optional[int] = self.mid_block(_lowerCamelCase ) # post-process __SCREAMING_SNAKE_CASE : Any = self.conv_norm_out(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.conv_act(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.conv_out(_lowerCamelCase ) return sample class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :Optional[Any]=3 , _lowerCamelCase :List[str]=3 , _lowerCamelCase :Tuple=("UpDecoderBlock2D",) , _lowerCamelCase :str=(6_4,) , _lowerCamelCase :List[str]=2 , _lowerCamelCase :str=3_2 , _lowerCamelCase :Optional[Any]="silu" , _lowerCamelCase :str="group" , ): super().__init__() __SCREAMING_SNAKE_CASE : List[str] = layers_per_block __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Convad( _lowerCamelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList([] ) __SCREAMING_SNAKE_CASE : List[str] = in_channels if norm_type == '''spatial''' else None # mid __SCREAMING_SNAKE_CASE : int = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=_lowerCamelCase , output_scale_factor=1 , resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=_lowerCamelCase , temb_channels=_lowerCamelCase , ) # up __SCREAMING_SNAKE_CASE : int = list(reversed(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[Any] = output_channel __SCREAMING_SNAKE_CASE : List[Any] = reversed_block_out_channels[i] __SCREAMING_SNAKE_CASE : Tuple = i == len(_lowerCamelCase ) - 1 __SCREAMING_SNAKE_CASE : List[str] = get_up_block( _lowerCamelCase , num_layers=self.layers_per_block + 1 , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , prev_output_channel=_lowerCamelCase , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=_lowerCamelCase , resnet_groups=_lowerCamelCase , attention_head_dim=_lowerCamelCase , temb_channels=_lowerCamelCase , resnet_time_scale_shift=_lowerCamelCase , ) self.up_blocks.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = output_channel # out if norm_type == "spatial": __SCREAMING_SNAKE_CASE : Union[str, Any] = SpatialNorm(block_out_channels[0] , _lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=_lowerCamelCase , eps=1e-6 ) __SCREAMING_SNAKE_CASE : int = nn.SiLU() __SCREAMING_SNAKE_CASE : Any = nn.Convad(block_out_channels[0] , _lowerCamelCase , 3 , padding=1 ) __SCREAMING_SNAKE_CASE : List[str] = False def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Tuple , _lowerCamelCase :Any=None ): __SCREAMING_SNAKE_CASE : List[str] = z __SCREAMING_SNAKE_CASE : Dict = self.conv_in(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(_lowerCamelCase :str ): def custom_forward(*_lowerCamelCase :Union[str, Any] ): return module(*_lowerCamelCase ) return custom_forward if is_torch_version('''>=''' , '''1.11.0''' ): # middle __SCREAMING_SNAKE_CASE : Optional[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , _lowerCamelCase , use_reentrant=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: __SCREAMING_SNAKE_CASE : Optional[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , use_reentrant=_lowerCamelCase ) else: # middle __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: __SCREAMING_SNAKE_CASE : Optional[Any] = torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase ) else: # middle __SCREAMING_SNAKE_CASE : List[str] = self.mid_block(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = sample.to(_lowerCamelCase ) # up for up_block in self.up_blocks: __SCREAMING_SNAKE_CASE : Dict = up_block(_lowerCamelCase , _lowerCamelCase ) # post-process if latent_embeds is None: __SCREAMING_SNAKE_CASE : int = self.conv_norm_out(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Tuple = self.conv_norm_out(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self.conv_act(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.conv_out(_lowerCamelCase ) return sample class snake_case ( nn.Module ): def __init__( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :Tuple=None , _lowerCamelCase :List[str]="random" , _lowerCamelCase :Dict=False , _lowerCamelCase :str=True ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = n_e __SCREAMING_SNAKE_CASE : int = vq_embed_dim __SCREAMING_SNAKE_CASE : Tuple = beta __SCREAMING_SNAKE_CASE : Any = legacy __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) __SCREAMING_SNAKE_CASE : Union[str, Any] = remap if self.remap is not None: self.register_buffer('''used''' , torch.tensor(np.load(self.remap ) ) ) __SCREAMING_SNAKE_CASE : str = self.used.shape[0] __SCREAMING_SNAKE_CASE : int = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": __SCREAMING_SNAKE_CASE : Optional[int] = self.re_embed __SCREAMING_SNAKE_CASE : Dict = self.re_embed + 1 print( f'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' f'''Using {self.unknown_index} for unknown indices.''' ) else: __SCREAMING_SNAKE_CASE : List[str] = n_e __SCREAMING_SNAKE_CASE : Tuple = sane_index_shape def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = inds.shape assert len(_lowerCamelCase ) > 1 __SCREAMING_SNAKE_CASE : int = inds.reshape(ishape[0] , -1 ) __SCREAMING_SNAKE_CASE : Optional[int] = self.used.to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = (inds[:, :, None] == used[None, None, ...]).long() __SCREAMING_SNAKE_CASE : Dict = match.argmax(-1 ) __SCREAMING_SNAKE_CASE : Any = match.sum(2 ) < 1 if self.unknown_index == "random": __SCREAMING_SNAKE_CASE : int = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.unknown_index return new.reshape(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : List[Any] = inds.shape assert len(_lowerCamelCase ) > 1 __SCREAMING_SNAKE_CASE : Optional[Any] = inds.reshape(ishape[0] , -1 ) __SCREAMING_SNAKE_CASE : Tuple = self.used.to(_lowerCamelCase ) if self.re_embed > self.used.shape[0]: # extra token __SCREAMING_SNAKE_CASE : Dict = 0 # simply set to zero __SCREAMING_SNAKE_CASE : Optional[int] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , _lowerCamelCase ) return back.reshape(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Union[str, Any] ): # reshape z -> (batch, height, width, channel) and flatten __SCREAMING_SNAKE_CASE : Tuple = z.permute(0 , 2 , 3 , 1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[int] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z __SCREAMING_SNAKE_CASE : Optional[int] = torch.argmin(torch.cdist(_lowerCamelCase , self.embedding.weight ) , dim=1 ) __SCREAMING_SNAKE_CASE : Tuple = self.embedding(_lowerCamelCase ).view(z.shape ) __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : List[Any] = None # compute loss for embedding if not self.legacy: __SCREAMING_SNAKE_CASE : Optional[int] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: __SCREAMING_SNAKE_CASE : Dict = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients __SCREAMING_SNAKE_CASE : Optional[Any] = z + (z_q - z).detach() # reshape back to match original input shape __SCREAMING_SNAKE_CASE : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: __SCREAMING_SNAKE_CASE : List[str] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis __SCREAMING_SNAKE_CASE : Optional[int] = self.remap_to_used(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: __SCREAMING_SNAKE_CASE : Any = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] ): # shape specifying (batch, height, width, channel) if self.remap is not None: __SCREAMING_SNAKE_CASE : Tuple = indices.reshape(shape[0] , -1 ) # add batch axis __SCREAMING_SNAKE_CASE : Optional[Any] = self.unmap_to_all(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = indices.reshape(-1 ) # flatten again # get quantized latent vectors __SCREAMING_SNAKE_CASE : str = self.embedding(_lowerCamelCase ) if shape is not None: __SCREAMING_SNAKE_CASE : Any = z_q.view(_lowerCamelCase ) # reshape back to match original input shape __SCREAMING_SNAKE_CASE : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class snake_case ( __UpperCAmelCase ): def __init__( self :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :Dict=False ): __SCREAMING_SNAKE_CASE : List[str] = parameters __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = torch.chunk(_lowerCamelCase , 2 , dim=1 ) __SCREAMING_SNAKE_CASE : List[str] = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = deterministic __SCREAMING_SNAKE_CASE : Optional[Any] = torch.exp(0.5 * self.logvar ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.exp(self.logvar ) if self.deterministic: __SCREAMING_SNAKE_CASE : str = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[torch.Generator] = None ): # make sure sample is on the same device as the parameters and has same dtype __SCREAMING_SNAKE_CASE : Dict = randn_tensor( self.mean.shape , generator=_lowerCamelCase , device=self.parameters.device , dtype=self.parameters.dtype ) __SCREAMING_SNAKE_CASE : Any = self.mean + self.std * sample return x def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :int=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Union[str, Any]=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.mean
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging _lowerCamelCase = logging.get_logger(__name__) class snake_case ( __UpperCAmelCase ): def __init__( self :str , _lowerCamelCase :Optional[Any]=None , **_lowerCamelCase :Optional[int] ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _lowerCamelCase , ) super().__init__(args=_lowerCamelCase , **_lowerCamelCase )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 lowerCamelCase__ = jnp.floataa lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): super().setup() __SCREAMING_SNAKE_CASE : List[Any] = nn.Dense(5 , dtype=self.dtype ) def __call__( self :Tuple , *_lowerCamelCase :Tuple , **_lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Any = super().__call__(*_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : str , lowercase_ : Any , lowercase_ : Any , lowercase_ : Dict ): '''simple docstring''' def cross_entropy(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : Dict=None ): __SCREAMING_SNAKE_CASE : Optional[Any] = logits.shape[-1] __SCREAMING_SNAKE_CASE : int = (labels[..., None] == jnp.arange(lowercase_ )[None]).astype('''f4''' ) __SCREAMING_SNAKE_CASE : int = jax.nn.log_softmax(lowercase_ , axis=-1 ) __SCREAMING_SNAKE_CASE : Dict = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: __SCREAMING_SNAKE_CASE : Any = reduction(lowercase_ ) return loss __SCREAMING_SNAKE_CASE : Optional[Any] = partial(lowercase_ , reduction=jnp.mean ) __SCREAMING_SNAKE_CASE : Optional[Any] = cross_entropy(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = cross_entropy(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = cross_entropy(lowercase_ , lowercase_ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class snake_case : lowerCamelCase__ = "google/bigbird-roberta-base" lowerCamelCase__ = 3000 lowerCamelCase__ = 10500 lowerCamelCase__ = 128 lowerCamelCase__ = 3 lowerCamelCase__ = 1 lowerCamelCase__ = 5 # tx_args lowerCamelCase__ = 3e-5 lowerCamelCase__ = 0.0 lowerCamelCase__ = 20000 lowerCamelCase__ = 0.0_0_9_5 lowerCamelCase__ = "bigbird-roberta-natural-questions" lowerCamelCase__ = "training-expt" lowerCamelCase__ = "data/nq-training.jsonl" lowerCamelCase__ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): os.makedirs(self.base_dir , exist_ok=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = os.path.join(self.base_dir , self.save_dir ) __SCREAMING_SNAKE_CASE : Dict = self.batch_size_per_device * jax.device_count() @dataclass class snake_case : lowerCamelCase__ = 42 lowerCamelCase__ = 4096 # no dynamic padding on TPUs def __call__( self :List[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Any = self.collate_fn(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = jax.tree_util.tree_map(_lowerCamelCase , _lowerCamelCase ) return batch def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.fetch_inputs(features['''input_ids'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''input_ids''': jnp.array(_lowerCamelCase , dtype=jnp.intaa ), '''attention_mask''': jnp.array(_lowerCamelCase , dtype=jnp.intaa ), '''start_labels''': jnp.array(features['''start_token'''] , dtype=jnp.intaa ), '''end_labels''': jnp.array(features['''end_token'''] , dtype=jnp.intaa ), '''pooled_labels''': jnp.array(features['''category'''] , dtype=jnp.intaa ), } return batch def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :list ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [self._fetch_inputs(_lowerCamelCase ) for ids in input_ids] return zip(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :list ): __SCREAMING_SNAKE_CASE : List[Any] = [1 for _ in range(len(_lowerCamelCase ) )] while len(_lowerCamelCase ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : Optional[int]=None ): '''simple docstring''' if seed is not None: __SCREAMING_SNAKE_CASE : Optional[int] = dataset.shuffle(seed=lowercase_ ) for i in range(len(lowercase_ ) // batch_size ): __SCREAMING_SNAKE_CASE : str = dataset[i * batch_size : (i + 1) * batch_size] yield dict(lowercase_ ) @partial(jax.pmap , axis_name='''batch''' ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Tuple , **lowercase_ : int ): '''simple docstring''' def loss_fn(lowercase_ : List[Any] ): __SCREAMING_SNAKE_CASE : Any = model_inputs.pop('''start_labels''' ) __SCREAMING_SNAKE_CASE : List[str] = model_inputs.pop('''end_labels''' ) __SCREAMING_SNAKE_CASE : List[Any] = model_inputs.pop('''pooled_labels''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = state.apply_fn(**lowercase_ , params=lowercase_ , dropout_rng=lowercase_ , train=lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = outputs return state.loss_fn( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = jax.random.split(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = jax.value_and_grad(lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = grad_fn(state.params ) __SCREAMING_SNAKE_CASE : Any = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) __SCREAMING_SNAKE_CASE : Optional[int] = jax.lax.pmean(lowercase_ , '''batch''' ) __SCREAMING_SNAKE_CASE : Optional[int] = state.apply_gradients(grads=lowercase_ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name='''batch''' ) def lowerCAmelCase_ ( lowercase_ : str , **lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = model_inputs.pop('''start_labels''' ) __SCREAMING_SNAKE_CASE : Tuple = model_inputs.pop('''end_labels''' ) __SCREAMING_SNAKE_CASE : List[Any] = model_inputs.pop('''pooled_labels''' ) __SCREAMING_SNAKE_CASE : Any = state.apply_fn(**lowercase_ , params=state.params , train=lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = outputs __SCREAMING_SNAKE_CASE : List[Any] = state.loss_fn(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : str = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) return metrics class snake_case ( train_state.TrainState ): lowerCamelCase__ = struct.field(pytree_node=__UpperCAmelCase ) @dataclass class snake_case : lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = None def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Union[str, Any]=None ): __SCREAMING_SNAKE_CASE : int = model.params __SCREAMING_SNAKE_CASE : Union[str, Any] = TrainState.create( apply_fn=model.__call__ , params=_lowerCamelCase , tx=_lowerCamelCase , loss_fn=_lowerCamelCase , ) if ckpt_dir is not None: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = restore_checkpoint(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = { '''lr''': args.lr, '''init_lr''': args.init_lr, '''warmup_steps''': args.warmup_steps, '''num_train_steps''': num_train_steps, '''weight_decay''': args.weight_decay, } __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = build_tx(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = train_state.TrainState( step=_lowerCamelCase , apply_fn=model.__call__ , params=_lowerCamelCase , tx=_lowerCamelCase , opt_state=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Any = args __SCREAMING_SNAKE_CASE : Any = data_collator __SCREAMING_SNAKE_CASE : int = lr __SCREAMING_SNAKE_CASE : Tuple = params __SCREAMING_SNAKE_CASE : int = jax_utils.replicate(_lowerCamelCase ) return state def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.args __SCREAMING_SNAKE_CASE : Any = len(_lowerCamelCase ) // args.batch_size __SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.split(_lowerCamelCase , jax.device_count() ) for epoch in range(args.max_epochs ): __SCREAMING_SNAKE_CASE : Dict = jnp.array(0 , dtype=jnp.floataa ) __SCREAMING_SNAKE_CASE : str = get_batched_dataset(_lowerCamelCase , args.batch_size , seed=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = 0 for batch in tqdm(_lowerCamelCase , total=_lowerCamelCase , desc=f'''Running EPOCH-{epoch}''' ): __SCREAMING_SNAKE_CASE : List[str] = self.data_collator(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = self.train_step_fn(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 if i % args.logging_steps == 0: __SCREAMING_SNAKE_CASE : int = jax_utils.unreplicate(state.step ) __SCREAMING_SNAKE_CASE : Optional[Any] = running_loss.item() / i __SCREAMING_SNAKE_CASE : List[Any] = self.scheduler_fn(state_step - 1 ) __SCREAMING_SNAKE_CASE : List[str] = self.evaluate(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = { '''step''': state_step.item(), '''eval_loss''': eval_loss.item(), '''tr_loss''': tr_loss, '''lr''': lr.item(), } tqdm.write(str(_lowerCamelCase ) ) self.logger.log(_lowerCamelCase , commit=_lowerCamelCase ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Dict = get_batched_dataset(_lowerCamelCase , self.args.batch_size ) __SCREAMING_SNAKE_CASE : List[Any] = len(_lowerCamelCase ) // self.args.batch_size __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(0 , dtype=jnp.floataa ) __SCREAMING_SNAKE_CASE : Optional[int] = 0 for batch in tqdm(_lowerCamelCase , total=_lowerCamelCase , desc='''Evaluating ... ''' ): __SCREAMING_SNAKE_CASE : Optional[int] = self.data_collator(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.val_step_fn(_lowerCamelCase , **_lowerCamelCase ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :str , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[Any] = jax_utils.unreplicate(_lowerCamelCase ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=''' ... ''' ) self.model_save_fn(_lowerCamelCase , params=state.params ) with open(os.path.join(_lowerCamelCase , '''opt_state.msgpack''' ) , '''wb''' ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(_lowerCamelCase , '''args.joblib''' ) ) joblib.dump(self.data_collator , os.path.join(_lowerCamelCase , '''data_collator.joblib''' ) ) with open(os.path.join(_lowerCamelCase , '''training_state.json''' ) , '''w''' ) as f: json.dump({'''step''': state.step.item()} , _lowerCamelCase ) print('''DONE''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] ): '''simple docstring''' print(F'''RESTORING CHECKPOINT FROM {save_dir}''' , end=''' ... ''' ) with open(os.path.join(lowercase_ , '''flax_model.msgpack''' ) , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = from_bytes(state.params , f.read() ) with open(os.path.join(lowercase_ , '''opt_state.msgpack''' ) , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : Optional[Any] = from_bytes(state.opt_state , f.read() ) __SCREAMING_SNAKE_CASE : Dict = joblib.load(os.path.join(lowercase_ , '''args.joblib''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = joblib.load(os.path.join(lowercase_ , '''data_collator.joblib''' ) ) with open(os.path.join(lowercase_ , '''training_state.json''' ) , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Any = json.load(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = training_state['''step'''] print('''DONE''' ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = num_train_steps - warmup_steps __SCREAMING_SNAKE_CASE : Optional[int] = optax.linear_schedule(init_value=lowercase_ , end_value=lowercase_ , transition_steps=lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = optax.linear_schedule(init_value=lowercase_ , end_value=1E-7 , transition_steps=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : int , lowercase_ : List[str] ): '''simple docstring''' def weight_decay_mask(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : str = traverse_util.flatten_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : Any = {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()} return traverse_util.unflatten_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : int = scheduler_fn(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = optax.adamw(learning_rate=lowercase_ , weight_decay=lowercase_ , mask=lowercase_ ) return tx, lr
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionPipeline.from_pretrained(lowercase_ , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors __SCREAMING_SNAKE_CASE : List[str] = load_file(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = key.split('''.''' )[0].split(LORA_PREFIX_TEXT_ENCODER + '''_''' )[-1].split('''_''' ) __SCREAMING_SNAKE_CASE : List[Any] = pipeline.text_encoder else: __SCREAMING_SNAKE_CASE : Union[str, Any] = key.split('''.''' )[0].split(LORA_PREFIX_UNET + '''_''' )[-1].split('''_''' ) __SCREAMING_SNAKE_CASE : Optional[int] = pipeline.unet # find the target layer __SCREAMING_SNAKE_CASE : Tuple = layer_infos.pop(0 ) while len(lowercase_ ) > -1: try: __SCREAMING_SNAKE_CASE : Dict = curr_layer.__getattr__(lowercase_ ) if len(lowercase_ ) > 0: __SCREAMING_SNAKE_CASE : List[Any] = layer_infos.pop(0 ) elif len(lowercase_ ) == 0: break except Exception: if len(lowercase_ ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: __SCREAMING_SNAKE_CASE : Dict = layer_infos.pop(0 ) __SCREAMING_SNAKE_CASE : List[Any] = [] if "lora_down" in key: pair_keys.append(key.replace('''lora_down''' , '''lora_up''' ) ) pair_keys.append(lowercase_ ) else: pair_keys.append(lowercase_ ) pair_keys.append(key.replace('''lora_up''' , '''lora_down''' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) __SCREAMING_SNAKE_CASE : Optional[Any] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ).unsqueeze(2 ).unsqueeze(3 ) else: __SCREAMING_SNAKE_CASE : Tuple = state_dict[pair_keys[0]].to(torch.floataa ) __SCREAMING_SNAKE_CASE : List[Any] = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ) # update visited list for item in pair_keys: visited.append(lowercase_ ) return pipeline if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''--base_model_path''', default=None, type=str, required=True, help='''Path to the base model in diffusers format.''' ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--lora_prefix_unet''', default='''lora_unet''', type=str, help='''The prefix of UNet weight in safetensors''' ) parser.add_argument( '''--lora_prefix_text_encoder''', default='''lora_te''', type=str, help='''The prefix of text encoder weight in safetensors''', ) parser.add_argument('''--alpha''', default=0.75, type=float, help='''The merging ratio in W = W0 + alpha * deltaW''') parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''' ) parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') _lowerCamelCase = parser.parse_args() _lowerCamelCase = args.base_model_path _lowerCamelCase = args.checkpoint_path _lowerCamelCase = args.dump_path _lowerCamelCase = args.lora_prefix_unet _lowerCamelCase = args.lora_prefix_text_encoder _lowerCamelCase = args.alpha _lowerCamelCase = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) _lowerCamelCase = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar _lowerCamelCase = TypeVar('''T''') class snake_case ( Generic[T] ): def __init__( self :List[str] , _lowerCamelCase :T ): __SCREAMING_SNAKE_CASE : Optional[Any] = data __SCREAMING_SNAKE_CASE : List[Any] = self __SCREAMING_SNAKE_CASE : Dict = 0 class snake_case ( Generic[T] ): def __init__( self :Union[str, Any] ): # map from node name to the node object __SCREAMING_SNAKE_CASE : dict[T, DisjointSetTreeNode[T]] = {} def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :T ): # create a new set with x as its member __SCREAMING_SNAKE_CASE : List[str] = DisjointSetTreeNode(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :T ): # find the set x belongs to (with path-compression) __SCREAMING_SNAKE_CASE : List[Any] = self.map[data] if elem_ref != elem_ref.parent: __SCREAMING_SNAKE_CASE : Dict = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :DisjointSetTreeNode[T] , _lowerCamelCase :DisjointSetTreeNode[T] ): # helper function for union operation if nodea.rank > nodea.rank: __SCREAMING_SNAKE_CASE : Optional[Any] = nodea else: __SCREAMING_SNAKE_CASE : Union[str, Any] = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :T , _lowerCamelCase :T ): # merge 2 disjoint sets self.link(self.find_set(_lowerCamelCase ) , self.find_set(_lowerCamelCase ) ) class snake_case ( Generic[T] ): def __init__( self :str ): # connections: map from the node to the neighbouring nodes (with weights) __SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :T ): # add a node ONLY if its not present in the graph if node not in self.connections: __SCREAMING_SNAKE_CASE : Tuple = {} def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :T , _lowerCamelCase :T , _lowerCamelCase :int ): # add an edge with the given weight self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = weight __SCREAMING_SNAKE_CASE : Any = weight def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = [] __SCREAMING_SNAKE_CASE : Tuple = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda _lowerCamelCase : x[2] ) # creating the disjoint set __SCREAMING_SNAKE_CASE : Optional[int] = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_lowerCamelCase ) # MST generation __SCREAMING_SNAKE_CASE : Dict = 0 __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : Optional[int] = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = edges[index] index += 1 __SCREAMING_SNAKE_CASE : Optional[Any] = disjoint_set.find_set(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = disjoint_set.find_set(_lowerCamelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) disjoint_set.union(_lowerCamelCase , _lowerCamelCase ) return graph
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 10**9 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = 1 __SCREAMING_SNAKE_CASE : Optional[int] = 2 __SCREAMING_SNAKE_CASE : List[Any] = 0 __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value __SCREAMING_SNAKE_CASE : Tuple = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class snake_case : lowerCamelCase__ = field( metadata={'''help''': '''The output directory where the model will be written.'''} , ) lowerCamelCase__ = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) } , ) lowerCamelCase__ = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) } , ) lowerCamelCase__ = field( default=__UpperCAmelCase , metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) lowerCamelCase__ = field( default=__UpperCAmelCase , metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = HfArgumentParser((ModelArguments,) ) ((__SCREAMING_SNAKE_CASE) , ) : List[Any] = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed __SCREAMING_SNAKE_CASE : List[Any] = True __SCREAMING_SNAKE_CASE : Dict = True __SCREAMING_SNAKE_CASE : Dict = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=lowercase_ , decoder_config=lowercase_ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens __SCREAMING_SNAKE_CASE : str = decoder_config.decoder_start_token_id __SCREAMING_SNAKE_CASE : int = decoder_config.pad_token_id if decoder_start_token_id is None: __SCREAMING_SNAKE_CASE : List[str] = decoder_config.bos_token_id if pad_token_id is None: __SCREAMING_SNAKE_CASE : List[Any] = decoder_config.eos_token_id # This is necessary to make Flax's generate() work __SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_config.eos_token_id __SCREAMING_SNAKE_CASE : str = decoder_start_token_id __SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) __SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) __SCREAMING_SNAKE_CASE : Any = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" _lowerCamelCase = {} def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int , lowercase_ : int ): '''simple docstring''' if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on __SCREAMING_SNAKE_CASE : List[Any] = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one __SCREAMING_SNAKE_CASE : Optional[Any] = _calculate(days - 1 , lowercase_ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 __SCREAMING_SNAKE_CASE : Optional[Any] = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter __SCREAMING_SNAKE_CASE : List[str] = _calculate(days - 1 , lowercase_ , 0 ) __SCREAMING_SNAKE_CASE : Optional[int] = state_late + state_absent + state_ontime __SCREAMING_SNAKE_CASE : Any = prizestrings return prizestrings def lowerCAmelCase_ ( lowercase_ : int = 30 ): '''simple docstring''' return _calculate(lowercase_ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" from __future__ import annotations from math import gcd def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int = 2 , lowercase_ : int = 1 , lowercase_ : int = 3 , ): '''simple docstring''' if num < 2: raise ValueError('''The input value cannot be less than 2''' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(lowercase_ : int , lowercase_ : int , lowercase_ : int ) -> int: return (pow(lowercase_ , 2 ) + step) % modulus for _ in range(lowercase_ ): # These track the position within the cycle detection logic. __SCREAMING_SNAKE_CASE : Any = seed __SCREAMING_SNAKE_CASE : str = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. __SCREAMING_SNAKE_CASE : List[str] = rand_fn(lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = rand_fn(lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Any = rand_fn(lowercase_ , lowercase_ , lowercase_ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. __SCREAMING_SNAKE_CASE : Union[str, Any] = gcd(hare - tortoise , lowercase_ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. __SCREAMING_SNAKE_CASE : Optional[int] = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''num''', type=int, help='''The value to find a divisor of''', ) parser.add_argument( '''--attempts''', type=int, default=3, help='''The number of attempts before giving up''', ) _lowerCamelCase = parser.parse_args() _lowerCamelCase = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f'{args.num} is probably prime') else: _lowerCamelCase = args.num // divisor print(f'{args.num} = {divisor} * {quotient}')
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model _lowerCamelCase = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[int]=None ): '''simple docstring''' if rng is None: __SCREAMING_SNAKE_CASE : Dict = random.Random() __SCREAMING_SNAKE_CASE : List[str] = 1 for dim in shape: total_dims *= dim __SCREAMING_SNAKE_CASE : Tuple = [] for _ in range(lowercase_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array(lowercase_ , dtype=jnp.intaa ).reshape(lowercase_ ) return output def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Dict=None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor(lowercase_ , vocab_size=2 , rng=lowercase_ ) # make sure that at least one token is attended to for each batch __SCREAMING_SNAKE_CASE : Tuple = 1 return attn_mask @require_flax class snake_case : lowerCamelCase__ = None lowerCamelCase__ = () def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __SCREAMING_SNAKE_CASE : int = 2 __SCREAMING_SNAKE_CASE : Any = inputs['''input_ids'''].shape[-1] // 2 __SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''input_ids'''][:max_batch_size, :sequence_length] __SCREAMING_SNAKE_CASE : List[str] = jnp.ones_like(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __SCREAMING_SNAKE_CASE : Union[str, Any] = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __SCREAMING_SNAKE_CASE : Optional[int] = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Optional[Any] = max_length __SCREAMING_SNAKE_CASE : List[Any] = 0 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model_class.__name__[4:] # Skip the "Flax" at the beginning __SCREAMING_SNAKE_CASE : Optional[int] = getattr(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = pt_model_class(_lowerCamelCase ).eval() __SCREAMING_SNAKE_CASE : Any = load_flax_weights_in_pytorch_model(_lowerCamelCase , flax_model.params ) __SCREAMING_SNAKE_CASE : Any = flax_model.generate(_lowerCamelCase ).sequences __SCREAMING_SNAKE_CASE : str = pt_model.generate(torch.tensor(_lowerCamelCase , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __SCREAMING_SNAKE_CASE : Optional[Any] = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Dict = max_length for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = jit(model.generate ) __SCREAMING_SNAKE_CASE : List[str] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : Optional[Any] = True __SCREAMING_SNAKE_CASE : List[str] = max_length for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = jit(model.generate ) __SCREAMING_SNAKE_CASE : Any = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : str = max_length __SCREAMING_SNAKE_CASE : List[Any] = 2 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[str] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = jit(model.generate ) __SCREAMING_SNAKE_CASE : Optional[int] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : List[Any] = False __SCREAMING_SNAKE_CASE : Optional[Any] = max_length __SCREAMING_SNAKE_CASE : Dict = 2 __SCREAMING_SNAKE_CASE : int = 2 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : Any = True __SCREAMING_SNAKE_CASE : int = max_length __SCREAMING_SNAKE_CASE : Dict = 0.8 __SCREAMING_SNAKE_CASE : int = 1_0 __SCREAMING_SNAKE_CASE : List[str] = 0.3 __SCREAMING_SNAKE_CASE : Optional[Any] = 1 __SCREAMING_SNAKE_CASE : Optional[Any] = 8 __SCREAMING_SNAKE_CASE : Optional[int] = 9 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[str] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = jit(model.generate ) __SCREAMING_SNAKE_CASE : str = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : Tuple = max_length __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 __SCREAMING_SNAKE_CASE : str = 8 __SCREAMING_SNAKE_CASE : Optional[int] = 9 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : Optional[int] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = jit(model.generate ) __SCREAMING_SNAKE_CASE : str = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self._get_input_ids_and_config() __SCREAMING_SNAKE_CASE : List[str] = max_length __SCREAMING_SNAKE_CASE : List[Any] = 2 __SCREAMING_SNAKE_CASE : Optional[Any] = 1 __SCREAMING_SNAKE_CASE : int = 8 __SCREAMING_SNAKE_CASE : int = 9 for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jit(model.generate ) __SCREAMING_SNAKE_CASE : Optional[int] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self._get_input_ids_and_config() # pad attention mask on the left __SCREAMING_SNAKE_CASE : Optional[int] = attention_mask.at[(0, 0)].set(0 ) __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Optional[Any] = max_length for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[str] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = jit(model.generate ) __SCREAMING_SNAKE_CASE : Optional[Any] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self._get_input_ids_and_config() # pad attention mask on the left __SCREAMING_SNAKE_CASE : List[Any] = attention_mask.at[(0, 0)].set(0 ) __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : List[str] = max_length for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = jit(model.generate ) __SCREAMING_SNAKE_CASE : List[str] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self._get_input_ids_and_config() # pad attention mask on the left __SCREAMING_SNAKE_CASE : Dict = attention_mask.at[(0, 0)].set(0 ) __SCREAMING_SNAKE_CASE : Tuple = 2 __SCREAMING_SNAKE_CASE : Tuple = max_length for model_class in self.all_generative_model_classes: __SCREAMING_SNAKE_CASE : List[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = jit(model.generate ) __SCREAMING_SNAKE_CASE : Optional[Any] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert''' ) __SCREAMING_SNAKE_CASE : Dict = FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) __SCREAMING_SNAKE_CASE : Dict = '''Hello world''' __SCREAMING_SNAKE_CASE : int = tokenizer(_lowerCamelCase , return_tensors='''np''' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(_lowerCamelCase , '''do_samples''' ): model.generate(_lowerCamelCase , do_samples=_lowerCamelCase ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(_lowerCamelCase , '''foo''' ): __SCREAMING_SNAKE_CASE : int = {'''foo''': '''bar'''} model.generate(_lowerCamelCase , **_lowerCamelCase )
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :Optional[int] , _lowerCamelCase :Any , _lowerCamelCase :Dict=7 , _lowerCamelCase :Tuple=3 , _lowerCamelCase :List[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Any=True , _lowerCamelCase :str=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :List[Any]=1 / 2_5_5 , _lowerCamelCase :Dict=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :int=[0.5, 0.5, 0.5] , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : str = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : Dict = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : int = num_channels __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : int = max_resolution __SCREAMING_SNAKE_CASE : Optional[int] = do_resize __SCREAMING_SNAKE_CASE : List[str] = size __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : List[str] = rescale_factor __SCREAMING_SNAKE_CASE : Tuple = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : str = image_std __SCREAMING_SNAKE_CASE : List[str] = do_pad def SCREAMING_SNAKE_CASE_ ( self :str ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :int , _lowerCamelCase :Union[str, Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : Optional[int] = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : Optional[int] = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : Dict = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Tuple = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : Optional[Any] = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[Any] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[int] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = DetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = DetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_rescale''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''rescale_factor''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_pad''' ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : int = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :str ): # Initialize image_processing __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Tuple = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # prepare image and target __SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Any = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : str = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' ) __SCREAMING_SNAKE_CASE : List[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : str = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : str = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Dict = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : int = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : int = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Tuple = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : str = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Union[str, Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : str = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : float , lowercase_ : list[float] ): '''simple docstring''' if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) __SCREAMING_SNAKE_CASE : Any = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowercase_ ) ) return round(lowercase_ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = StableDiffusionInstructPixaPixPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE_ ( self :int ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=8 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) __SCREAMING_SNAKE_CASE : Dict = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) __SCREAMING_SNAKE_CASE : Dict = CLIPTextModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __SCREAMING_SNAKE_CASE : List[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :Dict=0 ): __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE : int = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' ) if str(_lowerCamelCase ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : int = torch.manual_seed(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''image_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() __SCREAMING_SNAKE_CASE : List[str] = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = '''french fries''' __SCREAMING_SNAKE_CASE : List[str] = sd_pipe(**_lowerCamelCase , negative_prompt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = output.images __SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Dict = np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : str = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = [inputs['''prompt''']] * 2 __SCREAMING_SNAKE_CASE : int = np.array(inputs['''image'''] ).astype(np.floataa ) / 2_5_5.0 __SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = image / 2 + 0.5 __SCREAMING_SNAKE_CASE : Any = image.permute(0 , 3 , 1 , 2 ) __SCREAMING_SNAKE_CASE : int = image.repeat(2 , 1 , 1 , 1 ) __SCREAMING_SNAKE_CASE : int = sd_pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Tuple = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = sd_pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Optional[Any] = [round(_lowerCamelCase , 4 ) for x in image_slice.flatten().tolist()] print(''','''.join([str(_lowerCamelCase ) for x in slice] ) ) assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Dict = np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :Dict ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = VaeImageProcessor(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**self.get_dummy_inputs_by_type(_lowerCamelCase , input_image_type='''pt''' ) )[0] __SCREAMING_SNAKE_CASE : Optional[int] = components['''vae'''] __SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs_by_type(_lowerCamelCase , input_image_type='''pt''' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): __SCREAMING_SNAKE_CASE : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() __SCREAMING_SNAKE_CASE : Optional[int] = pipe(**_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(_lowerCamelCase , 1e-4 , '''passing latents as image input generate different result from passing image''' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Tuple=0 ): __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = load_image( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg''' ) __SCREAMING_SNAKE_CASE : Tuple = { '''prompt''': '''turn him into a cyborg''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''image_guidance_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_inputs() __SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : str = self.get_inputs() __SCREAMING_SNAKE_CASE : Dict = pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : Dict = np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : List[str] = self.get_inputs() __SCREAMING_SNAKE_CASE : Dict = pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : str = np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = 0 def callback_fn(_lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :torch.FloatTensor ) -> None: __SCREAMING_SNAKE_CASE : Optional[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __SCREAMING_SNAKE_CASE : List[Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) __SCREAMING_SNAKE_CASE : str = latents[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Optional[int] = np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: __SCREAMING_SNAKE_CASE : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) __SCREAMING_SNAKE_CASE : Optional[Any] = latents[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Tuple = np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 __SCREAMING_SNAKE_CASE : int = False __SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : Tuple = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : List[Any] = self.get_inputs() pipe(**_lowerCamelCase , callback=_lowerCamelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : List[str] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE : List[str] = self.get_inputs() __SCREAMING_SNAKE_CASE : List[Any] = pipe(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 1_0**9 def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 __SCREAMING_SNAKE_CASE : Optional[int] = inputs['''image'''].resize((5_0_4, 5_0_4) ) __SCREAMING_SNAKE_CASE : Tuple = '''timbrooks/instruct-pix2pix''' __SCREAMING_SNAKE_CASE : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( _lowerCamelCase , safety_checker=_lowerCamelCase , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : Optional[Any] = pipe(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] __SCREAMING_SNAKE_CASE : str = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 5_0_4, 3) __SCREAMING_SNAKE_CASE : List[str] = np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : list[list[int]] , lowercase_ : int , lowercase_ : int , lowercase_ : list[int] ): '''simple docstring''' if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def lowerCAmelCase_ ( lowercase_ : list[list[int]] , lowercase_ : list[int] , lowercase_ : int ): '''simple docstring''' if curr_ind == len(lowercase_ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(lowercase_ ) ): if valid_connection(lowercase_ , lowercase_ , lowercase_ , lowercase_ ): # Insert current vertex into path as next transition __SCREAMING_SNAKE_CASE : List[str] = next_ver # Validate created path if util_hamilton_cycle(lowercase_ , lowercase_ , curr_ind + 1 ): return True # Backtrack __SCREAMING_SNAKE_CASE : List[str] = -1 return False def lowerCAmelCase_ ( lowercase_ : list[list[int]] , lowercase_ : int = 0 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = [-1] * (len(lowercase_ ) + 1) # initialize start and end of path with starting index __SCREAMING_SNAKE_CASE : str = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(lowercase_ , lowercase_ , 1 ) else []
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" _lowerCamelCase = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' _lowerCamelCase = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] _lowerCamelCase = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" from typing import List import numpy as np def lowerCAmelCase_ ( lowercase_ : dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = {key: len(lowercase_ ) for key, value in gen_kwargs.items() if isinstance(lowercase_ , lowercase_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( '''Sharding is ambiguous for this dataset: ''' + '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n''' + '''\n'''.join(F'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() ) + '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ''' + '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.''' ) ) __SCREAMING_SNAKE_CASE : Dict = max(lists_lengths.values() , default=0 ) return max(1 , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = [] for group_idx in range(lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __SCREAMING_SNAKE_CASE : Optional[int] = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __SCREAMING_SNAKE_CASE : Any = range(lowercase_ , start + num_shards_to_add ) shards_indices_per_group.append(lowercase_ ) return shards_indices_per_group def lowerCAmelCase_ ( lowercase_ : dict , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = _number_of_shards_in_gen_kwargs(lowercase_ ) if num_shards == 1: return [dict(lowercase_ )] else: __SCREAMING_SNAKE_CASE : List[Any] = _distribute_shards(num_shards=lowercase_ , max_num_jobs=lowercase_ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(lowercase_ , lowercase_ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(lowercase_ ) ) ] def lowerCAmelCase_ ( lowercase_ : List[dict] ): '''simple docstring''' return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , lowercase_ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def lowerCAmelCase_ ( lowercase_ : np.random.Generator , lowercase_ : dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = {len(lowercase_ ) for value in gen_kwargs.values() if isinstance(lowercase_ , lowercase_ )} __SCREAMING_SNAKE_CASE : Dict = {} for size in list_sizes: __SCREAMING_SNAKE_CASE : int = list(range(lowercase_ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __SCREAMING_SNAKE_CASE : Union[str, Any] = dict(lowercase_ ) for key, value in shuffled_kwargs.items(): if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[Any] = [value[i] for i in indices_per_size[len(lowercase_ )]] return shuffled_kwargs
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :str , _lowerCamelCase :int=3 , _lowerCamelCase :List[Any]=3_2 , _lowerCamelCase :int=3 , _lowerCamelCase :Dict=1_0 , _lowerCamelCase :int=[8, 1_6, 3_2, 6_4] , _lowerCamelCase :List[Any]=[1, 1, 2, 1] , _lowerCamelCase :Tuple=True , _lowerCamelCase :List[str]=True , _lowerCamelCase :str="relu" , _lowerCamelCase :List[Any]=3 , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Optional[int]=["stage2", "stage3", "stage4"] , _lowerCamelCase :Optional[Any]=[2, 3, 4] , _lowerCamelCase :Tuple=1 , ): __SCREAMING_SNAKE_CASE : Dict = parent __SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size __SCREAMING_SNAKE_CASE : List[Any] = image_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels __SCREAMING_SNAKE_CASE : Any = embeddings_size __SCREAMING_SNAKE_CASE : Any = hidden_sizes __SCREAMING_SNAKE_CASE : int = depths __SCREAMING_SNAKE_CASE : Any = is_training __SCREAMING_SNAKE_CASE : List[str] = use_labels __SCREAMING_SNAKE_CASE : Any = hidden_act __SCREAMING_SNAKE_CASE : str = num_labels __SCREAMING_SNAKE_CASE : Tuple = scope __SCREAMING_SNAKE_CASE : Union[str, Any] = len(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = out_features __SCREAMING_SNAKE_CASE : Any = out_indices __SCREAMING_SNAKE_CASE : int = num_groups def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : List[str] = None if self.use_labels: __SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self :Dict ): return BitConfig( 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 , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = BitModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Any , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = self.num_labels __SCREAMING_SNAKE_CASE : int = BitForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :List[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = BitBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __SCREAMING_SNAKE_CASE : Tuple = None __SCREAMING_SNAKE_CASE : Tuple = BitBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = config_and_inputs __SCREAMING_SNAKE_CASE : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': BitModel, '''image-classification''': BitForImageClassification} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = BitModelTester(self ) __SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE_ ( self :Dict ): return @unittest.skip(reason='''Bit does not output attentions''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : str = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : str = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : List[Any] = model_class(config=_lowerCamelCase ) for name, module in model.named_modules(): if isinstance(_lowerCamelCase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): def check_hidden_states_output(_lowerCamelCase :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # Bit'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] , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : List[Any] = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: __SCREAMING_SNAKE_CASE : Optional[int] = layer_type __SCREAMING_SNAKE_CASE : Any = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE : Tuple = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = BitModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Any = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : Any = image_processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE : Any = model(**_lowerCamelCase ) # verify the logits __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[-0.6_5_2_6, -0.5_2_6_3, -1.4_3_9_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) @require_torch class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (BitBackbone,) if is_torch_available() else () lowerCamelCase__ = BitConfig lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = BitModelTester(self )
674
"""simple docstring""" 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 lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = 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''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str , lowercase_ : List[Any] , lowercase_ : Tuple ): '''simple docstring''' if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(lowercase_ , '''rb''' ) as fp: __SCREAMING_SNAKE_CASE : Tuple = pickle.load(lowercase_ , encoding='''latin1''' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) __SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file'''] print(F'''Save vocabulary to {pytorch_vocab_dump_path}''' ) __SCREAMING_SNAKE_CASE : Any = corpus.vocab.__dict__ torch.save(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = corpus.__dict__ corpus_dict_no_vocab.pop('''vocab''' , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + '''/''' + CORPUS_NAME print(F'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(lowercase_ , lowercase_ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = os.path.abspath(lowercase_ ) print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": __SCREAMING_SNAKE_CASE : Dict = TransfoXLConfig() else: __SCREAMING_SNAKE_CASE : List[Any] = TransfoXLConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : str = TransfoXLLMHeadModel(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = load_tf_weights_in_transfo_xl(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model __SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = os.path.join(lowercase_ , lowercase_ ) print(F'''Save PyTorch model to {os.path.abspath(lowercase_ )}''' ) torch.save(model.state_dict() , lowercase_ ) print(F'''Save configuration file to {os.path.abspath(lowercase_ )}''' ) with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the folder to store the PyTorch model or dataset/vocab.''', ) parser.add_argument( '''--tf_checkpoint_path''', default='''''', type=str, help='''An optional path to a TensorFlow checkpoint path to be converted.''', ) parser.add_argument( '''--transfo_xl_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--transfo_xl_dataset_file''', default='''''', type=str, help='''An optional dataset file to be converted in a vocabulary.''', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" _lowerCamelCase = { '''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 _lowerCamelCase = {value: key for key, value in MORSE_CODE_DICT.items()} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = '''Morse code here!''' print(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = encrypt(lowercase_ ) print(lowercase_ ) __SCREAMING_SNAKE_CASE : str = decrypt(lowercase_ ) print(lowercase_ ) if __name__ == "__main__": main()
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class snake_case ( __UpperCAmelCase ): @require_torch def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # 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 __SCREAMING_SNAKE_CASE : Optional[Any] = ''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' __SCREAMING_SNAKE_CASE : Optional[int] = ''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' __SCREAMING_SNAKE_CASE : Optional[int] = ''' import socket def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache __SCREAMING_SNAKE_CASE : List[str] = '''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 __SCREAMING_SNAKE_CASE : Dict = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed __SCREAMING_SNAKE_CASE : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files __SCREAMING_SNAKE_CASE : List[Any] = '''1''' __SCREAMING_SNAKE_CASE : Tuple = 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched __SCREAMING_SNAKE_CASE : Dict = ''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' __SCREAMING_SNAKE_CASE : List[str] = ''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' __SCREAMING_SNAKE_CASE : List[str] = ''' import socket def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache __SCREAMING_SNAKE_CASE : Dict = '''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 __SCREAMING_SNAKE_CASE : Optional[Any] = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed __SCREAMING_SNAKE_CASE : Tuple = self.get_env() __SCREAMING_SNAKE_CASE : List[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 SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # 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 __SCREAMING_SNAKE_CASE : int = ''' from transformers import BertConfig, BertModel, BertTokenizer ''' __SCREAMING_SNAKE_CASE : List[Any] = ''' mname = "hf-internal-testing/tiny-random-bert-sharded" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print("success") ''' __SCREAMING_SNAKE_CASE : str = ''' import socket def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") socket.socket = offline_socket ''' # baseline - just load from_pretrained with normal network __SCREAMING_SNAKE_CASE : Dict = [sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_env() __SCREAMING_SNAKE_CASE : 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() ) # next emulate no network __SCREAMING_SNAKE_CASE : int = [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 __SCREAMING_SNAKE_CASE : Union[str, Any] = '''1''' __SCREAMING_SNAKE_CASE : 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 SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[str] = ''' from transformers import pipeline ''' __SCREAMING_SNAKE_CASE : List[Any] = ''' mname = "hf-internal-testing/tiny-random-bert" pipe = pipeline(model=mname) ''' __SCREAMING_SNAKE_CASE : Tuple = ''' import socket def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") socket.socket = offline_socket ''' __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_env() __SCREAMING_SNAKE_CASE : Optional[Any] = '''1''' __SCREAMING_SNAKE_CASE : Optional[int] = [sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] __SCREAMING_SNAKE_CASE : Dict = 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Dict = ''' from transformers import AutoModel ''' __SCREAMING_SNAKE_CASE : Dict = ''' mname = "hf-internal-testing/test_dynamic_model" AutoModel.from_pretrained(mname, trust_remote_code=True) print("success") ''' # baseline - just load from_pretrained with normal network __SCREAMING_SNAKE_CASE : Any = [sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed __SCREAMING_SNAKE_CASE : int = self.get_env() __SCREAMING_SNAKE_CASE : Any = 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 __SCREAMING_SNAKE_CASE : Optional[Any] = '''1''' __SCREAMING_SNAKE_CASE : 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() )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = {'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SEWForCTC''', '''SEWForSequenceClassification''', '''SEWModel''', '''SEWPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase = ''' Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)["depth"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline("depth-estimation") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to("cuda") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to("cuda") >>> img = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/cat.png" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda") >>> prompt = "A robot, 4k photo" >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature" >>> generator = torch.Generator(device="cuda").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save("robot_cat.png") ``` ''' def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=8 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __SCREAMING_SNAKE_CASE : int = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class snake_case ( __UpperCAmelCase ): def __init__( self :List[Any] , _lowerCamelCase :UNetaDConditionModel , _lowerCamelCase :DDPMScheduler , _lowerCamelCase :VQModel , ): super().__init__() self.register_modules( unet=_lowerCamelCase , scheduler=_lowerCamelCase , movq=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Tuple , _lowerCamelCase :str , _lowerCamelCase :List[str] , _lowerCamelCase :Optional[int] , _lowerCamelCase :str , _lowerCamelCase :str ): if latents is None: __SCREAMING_SNAKE_CASE : Any = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase , device=_lowerCamelCase , dtype=_lowerCamelCase ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) __SCREAMING_SNAKE_CASE : Any = latents.to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = latents * scheduler.init_noise_sigma return latents def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __SCREAMING_SNAKE_CASE : str = torch.device(f'''cuda:{gpu_id}''' ) __SCREAMING_SNAKE_CASE : Tuple = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :str=0 ): if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) __SCREAMING_SNAKE_CASE : List[str] = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=_lowerCamelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __SCREAMING_SNAKE_CASE : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = cpu_offload_with_hook(_lowerCamelCase , _lowerCamelCase , prev_module_hook=_lowerCamelCase ) # We'll offload the last model manually. __SCREAMING_SNAKE_CASE : List[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_lowerCamelCase , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_lowerCamelCase ) def __call__( self :List[Any] , _lowerCamelCase :Union[torch.FloatTensor, List[torch.FloatTensor]] , _lowerCamelCase :Union[torch.FloatTensor, List[torch.FloatTensor]] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :int = 5_1_2 , _lowerCamelCase :int = 5_1_2 , _lowerCamelCase :int = 1_0_0 , _lowerCamelCase :float = 4.0 , _lowerCamelCase :int = 1 , _lowerCamelCase :Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCamelCase :Optional[torch.FloatTensor] = None , _lowerCamelCase :Optional[str] = "pil" , _lowerCamelCase :bool = True , ): __SCREAMING_SNAKE_CASE : Dict = self._execution_device __SCREAMING_SNAKE_CASE : List[str] = guidance_scale > 1.0 if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = torch.cat(_lowerCamelCase , dim=0 ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Any = torch.cat(_lowerCamelCase , dim=0 ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(_lowerCamelCase , dim=0 ) __SCREAMING_SNAKE_CASE : Any = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE : Any = image_embeds.repeat_interleave(_lowerCamelCase , dim=0 ) __SCREAMING_SNAKE_CASE : str = negative_image_embeds.repeat_interleave(_lowerCamelCase , dim=0 ) __SCREAMING_SNAKE_CASE : Dict = hint.repeat_interleave(_lowerCamelCase , dim=0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=_lowerCamelCase ) self.scheduler.set_timesteps(_lowerCamelCase , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.timesteps __SCREAMING_SNAKE_CASE : str = self.movq.config.latent_channels __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = downscale_height_and_width(_lowerCamelCase , _lowerCamelCase , self.movq_scale_factor ) # create initial latent __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(_lowerCamelCase ) ): # expand the latents if we are doing classifier free guidance __SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_embeds''': image_embeds, '''hint''': hint} __SCREAMING_SNAKE_CASE : Any = self.unet( sample=_lowerCamelCase , timestep=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , added_cond_kwargs=_lowerCamelCase , return_dict=_lowerCamelCase , )[0] if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = noise_pred.chunk(2 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = variance_pred.chunk(2 ) __SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase , )[0] # post-processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.movq.decode(_lowerCamelCase , force_not_quantize=_lowerCamelCase )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: __SCREAMING_SNAKE_CASE : Optional[Any] = image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE : List[Any] = image.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE : str = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowerCamelCase )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html _lowerCamelCase = '''platform''' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Optional[int] , lowercase_ : Optional[int]=None , lowercase_ : List[str]=None , lowercase_ : Optional[int]=None , lowercase_ : str=None , lowercase_ : Optional[int]=None , lowercase_ : Optional[int]=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE : int = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE : Any = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __SCREAMING_SNAKE_CASE : str = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __SCREAMING_SNAKE_CASE : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __SCREAMING_SNAKE_CASE : Any = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class snake_case : def __init__( self :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :int=1_3 , _lowerCamelCase :Optional[Any]=7 , _lowerCamelCase :List[Any]=True , _lowerCamelCase :List[str]=False , _lowerCamelCase :Dict=9_9 , _lowerCamelCase :Union[str, Any]=1_6 , _lowerCamelCase :Union[str, Any]=2 , _lowerCamelCase :List[Any]=4 , _lowerCamelCase :List[Any]=4 , _lowerCamelCase :Optional[int]="gelu" , _lowerCamelCase :Optional[Any]=0.1 , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :Tuple=3_2 , _lowerCamelCase :Any=2 , _lowerCamelCase :Union[str, Any]=1 , _lowerCamelCase :Optional[int]=0 , _lowerCamelCase :Optional[int]=0.0_2 , ): __SCREAMING_SNAKE_CASE : Optional[Any] = parent __SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size __SCREAMING_SNAKE_CASE : Union[str, Any] = seq_length __SCREAMING_SNAKE_CASE : Optional[int] = is_training __SCREAMING_SNAKE_CASE : Tuple = use_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers __SCREAMING_SNAKE_CASE : str = num_attention_heads __SCREAMING_SNAKE_CASE : int = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob __SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings __SCREAMING_SNAKE_CASE : List[Any] = eos_token_id __SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id __SCREAMING_SNAKE_CASE : Tuple = bos_token_id __SCREAMING_SNAKE_CASE : List[Any] = initializer_range def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __SCREAMING_SNAKE_CASE : Dict = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __SCREAMING_SNAKE_CASE : int = shift_tokens_right(_lowerCamelCase , 1 , 2 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[int] = prepare_blenderbot_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = 2_0 __SCREAMING_SNAKE_CASE : List[str] = model_class_name(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = model.encode(inputs_dict['''input_ids'''] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __SCREAMING_SNAKE_CASE : Dict = model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __SCREAMING_SNAKE_CASE : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE : Optional[int] = model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : str = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __SCREAMING_SNAKE_CASE : Dict = model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Dict = model.decode(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 2_0 __SCREAMING_SNAKE_CASE : Optional[int] = model_class_name(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model.encode(inputs_dict['''input_ids'''] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE : List[str] = model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE : str = model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __SCREAMING_SNAKE_CASE : int = model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Dict = model.decode(_lowerCamelCase , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) @require_flax class snake_case ( unittest.TestCase ): lowerCamelCase__ = 99 def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = np.array( [ [7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2], [5, 9_7, 1_7, 3_9, 9_4, 4_0, 2], [7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2], [8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2], [5_5, 1_3, 1_6, 5_8, 5, 2, 1], # note padding [6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2], [5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2], [4_8, 6_1, 9, 2_4, 7_1, 8_2, 2], [2_6, 1, 6_0, 4_8, 2_2, 1_3, 2], [2_1, 5, 6_2, 2_8, 1_4, 7_6, 2], [4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2], [7_0, 7_0, 5_0, 9, 2_8, 0, 2], ] , dtype=np.intaa , ) __SCREAMING_SNAKE_CASE : Tuple = input_ids.shape[0] __SCREAMING_SNAKE_CASE : Optional[Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=2_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=3_2 , decoder_ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self._get_config_and_data() __SCREAMING_SNAKE_CASE : List[Any] = FlaxBlenderbotForConditionalGeneration(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = lm_model(input_ids=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = BlenderbotConfig( vocab_size=self.vocab_size , d_model=1_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=4_8 , ) __SCREAMING_SNAKE_CASE : str = FlaxBlenderbotForConditionalGeneration(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : int = np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : int = lm_model(input_ids=_lowerCamelCase , decoder_input_ids=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : int = np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Any = shift_tokens_right(_lowerCamelCase , 1 , 2 ) __SCREAMING_SNAKE_CASE : List[str] = np.equal(_lowerCamelCase , 1 ).astype(np.floataa ).sum() __SCREAMING_SNAKE_CASE : List[Any] = np.equal(_lowerCamelCase , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_lowerCamelCase , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class snake_case ( __UpperCAmelCase , unittest.TestCase , __UpperCAmelCase ): lowerCamelCase__ = True lowerCamelCase__ = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) lowerCamelCase__ = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBlenderbotModelTester(self ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = model_class(_lowerCamelCase ) @jax.jit def encode_jitted(_lowerCamelCase :List[str] , _lowerCamelCase :Optional[int]=None , **_lowerCamelCase :Union[str, Any] ): return model.encode(input_ids=_lowerCamelCase , attention_mask=_lowerCamelCase ) with self.subTest('''JIT Enabled''' ): __SCREAMING_SNAKE_CASE : Dict = encode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE : Optional[int] = encode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_lowerCamelCase :int , _lowerCamelCase :Any , _lowerCamelCase :Optional[int] ): return model.decode( decoder_input_ids=_lowerCamelCase , decoder_attention_mask=_lowerCamelCase , encoder_outputs=_lowerCamelCase , ) with self.subTest('''JIT Enabled''' ): __SCREAMING_SNAKE_CASE : int = decode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE : Optional[int] = decode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE : Optional[int] = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __SCREAMING_SNAKE_CASE : Union[str, Any] = np.ones((1, 1) ) * model.config.eos_token_id __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : int = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 1_5, '''max_length''': 2_5} __SCREAMING_SNAKE_CASE : List[str] = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} __SCREAMING_SNAKE_CASE : Any = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''Sam'''] __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase , return_tensors='''jax''' ) __SCREAMING_SNAKE_CASE : List[Any] = model.generate(**_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''Sam is a great name. It means "sun" in Gaelic.''' __SCREAMING_SNAKE_CASE : str = tokenizer.batch_decode(_lowerCamelCase , **_lowerCamelCase ) assert generated_txt[0].strip() == tgt_text
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = { '''attention_cell''': '''multi_head''', '''num_layers''': 4, '''units''': 1024, '''hidden_size''': 768, '''max_length''': 512, '''num_heads''': 8, '''scaled''': True, '''dropout''': 0.1, '''use_residual''': True, '''embed_size''': 1024, '''embed_dropout''': 0.1, '''word_embed''': None, '''layer_norm_eps''': 1E-5, '''token_type_vocab_size''': 2, } __SCREAMING_SNAKE_CASE : Optional[int] = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __SCREAMING_SNAKE_CASE : Dict = BERTEncoder( attention_cell=predefined_args['''attention_cell'''] , num_layers=predefined_args['''num_layers'''] , units=predefined_args['''units'''] , hidden_size=predefined_args['''hidden_size'''] , max_length=predefined_args['''max_length'''] , num_heads=predefined_args['''num_heads'''] , scaled=predefined_args['''scaled'''] , dropout=predefined_args['''dropout'''] , output_attention=lowercase_ , output_all_encodings=lowercase_ , use_residual=predefined_args['''use_residual'''] , activation=predefined_args.get('''activation''' , '''gelu''' ) , layer_norm_eps=predefined_args.get('''layer_norm_eps''' , lowercase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __SCREAMING_SNAKE_CASE : Tuple = '''openwebtext_ccnews_stories_books_cased''' # Specify download folder to Gluonnlp's vocab __SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(get_home_dir() , '''models''' ) __SCREAMING_SNAKE_CASE : Dict = _load_vocab(lowercase_ , lowercase_ , lowercase_ , cls=lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = nlp.model.BERTModel( lowercase_ , len(lowercase_ ) , units=predefined_args['''units'''] , embed_size=predefined_args['''embed_size'''] , embed_dropout=predefined_args['''embed_dropout'''] , word_embed=predefined_args['''word_embed'''] , use_pooler=lowercase_ , use_token_type_embed=lowercase_ , token_type_vocab_size=predefined_args['''token_type_vocab_size'''] , use_classifier=lowercase_ , use_decoder=lowercase_ , ) original_bort.load_parameters(lowercase_ , cast_dtype=lowercase_ , ignore_extra=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''architectures''': ['''BertForMaskedLM'''], '''attention_probs_dropout_prob''': predefined_args['''dropout'''], '''hidden_act''': '''gelu''', '''hidden_dropout_prob''': predefined_args['''dropout'''], '''hidden_size''': predefined_args['''embed_size'''], '''initializer_range''': 0.02, '''intermediate_size''': predefined_args['''hidden_size'''], '''layer_norm_eps''': predefined_args['''layer_norm_eps'''], '''max_position_embeddings''': predefined_args['''max_length'''], '''model_type''': '''bort''', '''num_attention_heads''': predefined_args['''num_heads'''], '''num_hidden_layers''': predefined_args['''num_layers'''], '''pad_token_id''': 1, # 2 = BERT, 1 = RoBERTa '''type_vocab_size''': 1, # 2 = BERT, 1 = RoBERTa '''vocab_size''': len(lowercase_ ), } __SCREAMING_SNAKE_CASE : Optional[Any] = BertConfig.from_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForMaskedLM(lowercase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowercase_ : Union[str, Any] ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = hf_param.shape __SCREAMING_SNAKE_CASE : List[Any] = to_torch(params[gluon_param] ) __SCREAMING_SNAKE_CASE : Tuple = gluon_param.shape assert ( shape_hf == shape_gluon ), F'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , '''word_embed.0.weight''' ) __SCREAMING_SNAKE_CASE : List[Any] = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , '''encoder.position_weight''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , '''encoder.layer_norm.beta''' ) __SCREAMING_SNAKE_CASE : Any = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , '''encoder.layer_norm.gamma''' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __SCREAMING_SNAKE_CASE : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __SCREAMING_SNAKE_CASE : BertSelfAttention = layer.attention.self __SCREAMING_SNAKE_CASE : str = check_and_map_params( self_attn.key.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( self_attn.key.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __SCREAMING_SNAKE_CASE : int = check_and_map_params( self_attn.query.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( self_attn.query.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __SCREAMING_SNAKE_CASE : int = check_and_map_params( self_attn.value.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __SCREAMING_SNAKE_CASE : List[Any] = check_and_map_params( self_attn.value.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __SCREAMING_SNAKE_CASE : BertSelfOutput = layer.attention.output __SCREAMING_SNAKE_CASE : Any = check_and_map_params( self_output.dense.bias , F'''encoder.transformer_cells.{i}.proj.bias''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = check_and_map_params( self_output.dense.weight , F'''encoder.transformer_cells.{i}.proj.weight''' ) __SCREAMING_SNAKE_CASE : Any = check_and_map_params( self_output.LayerNorm.bias , F'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __SCREAMING_SNAKE_CASE : Tuple = check_and_map_params( self_output.LayerNorm.weight , F'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __SCREAMING_SNAKE_CASE : BertIntermediate = layer.intermediate __SCREAMING_SNAKE_CASE : Optional[Any] = check_and_map_params( intermediate.dense.bias , F'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = check_and_map_params( intermediate.dense.weight , F'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __SCREAMING_SNAKE_CASE : BertOutput = layer.output __SCREAMING_SNAKE_CASE : str = check_and_map_params( bert_output.dense.bias , F'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __SCREAMING_SNAKE_CASE : Optional[int] = check_and_map_params( bert_output.dense.weight , F'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __SCREAMING_SNAKE_CASE : Dict = check_and_map_params( bert_output.LayerNorm.bias , F'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __SCREAMING_SNAKE_CASE : List[str] = check_and_map_params( bert_output.LayerNorm.weight , F'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __SCREAMING_SNAKE_CASE : Optional[int] = RobertaTokenizer.from_pretrained('''roberta-base''' ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode_plus(lowercase_ )['''input_ids'''] # Get gluon output __SCREAMING_SNAKE_CASE : Any = mx.nd.array([input_ids] ) __SCREAMING_SNAKE_CASE : Optional[Any] = original_bort(inputs=lowercase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowercase_ ) __SCREAMING_SNAKE_CASE : str = BertModel.from_pretrained(lowercase_ ) hf_bort_model.eval() __SCREAMING_SNAKE_CASE : Dict = tokenizer.encode_plus(lowercase_ , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : List[Any] = hf_bort_model(**lowercase_ )[0] __SCREAMING_SNAKE_CASE : str = output_gluon[0].asnumpy() __SCREAMING_SNAKE_CASE : int = output_hf[0].detach().numpy() __SCREAMING_SNAKE_CASE : Union[str, Any] = np.max(np.abs(hf_layer - gluon_layer ) ).item() __SCREAMING_SNAKE_CASE : Tuple = np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) if success: print('''✔️ Both model do output the same tensors''' ) else: print('''❌ Both model do **NOT** output the same tensors''' ) print('''Absolute difference is:''' , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" class snake_case : def __init__( self :List[str] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Optional[int] = n __SCREAMING_SNAKE_CASE : Tuple = [None] * self.n __SCREAMING_SNAKE_CASE : Optional[int] = 0 # index of the first element __SCREAMING_SNAKE_CASE : Optional[int] = 0 __SCREAMING_SNAKE_CASE : Tuple = 0 def __len__( self :List[str] ): return self.size def SCREAMING_SNAKE_CASE_ ( self :Any ): return self.size == 0 def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return False if self.is_empty() else self.array[self.front] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Any ): if self.size >= self.n: raise Exception('''QUEUE IS FULL''' ) __SCREAMING_SNAKE_CASE : Tuple = data __SCREAMING_SNAKE_CASE : Dict = (self.rear + 1) % self.n self.size += 1 return self def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): if self.size == 0: raise Exception('''UNDERFLOW''' ) __SCREAMING_SNAKE_CASE : Optional[int] = self.array[self.front] __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : List[Any] = (self.front + 1) % self.n self.size -= 1 return temp
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Optional[int]="attention" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] __SCREAMING_SNAKE_CASE : Optional[int] = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] __SCREAMING_SNAKE_CASE : List[Any] = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] __SCREAMING_SNAKE_CASE : str = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int]=False ): '''simple docstring''' if split_mlp_wi: __SCREAMING_SNAKE_CASE : int = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] __SCREAMING_SNAKE_CASE : Tuple = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] __SCREAMING_SNAKE_CASE : str = (wi_a, wi_a) else: __SCREAMING_SNAKE_CASE : str = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] __SCREAMING_SNAKE_CASE : Optional[Any] = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Tuple , lowercase_ : List[str] , lowercase_ : int ): '''simple docstring''' return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def lowerCAmelCase_ ( lowercase_ : dict , *, lowercase_ : int , lowercase_ : bool ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = traverse_util.flatten_dict(variables['''target'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''/'''.join(lowercase_ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi __SCREAMING_SNAKE_CASE : Any = '''encoder/layers_0/mlp/wi_0/kernel''' in old print('''Split MLP:''' , lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = collections.OrderedDict() # Shared embeddings. __SCREAMING_SNAKE_CASE : str = old['''token_embedder/embedding'''] # Encoder. for i in range(lowercase_ ): # Block i, layer 0 (Self Attention). __SCREAMING_SNAKE_CASE : List[str] = tax_layer_norm_lookup(lowercase_ , lowercase_ , '''encoder''' , '''pre_attention_layer_norm''' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = tax_attention_lookup(lowercase_ , lowercase_ , '''encoder''' , '''attention''' ) __SCREAMING_SNAKE_CASE : Tuple = layer_norm __SCREAMING_SNAKE_CASE : Union[str, Any] = k.T __SCREAMING_SNAKE_CASE : List[Any] = o.T __SCREAMING_SNAKE_CASE : int = q.T __SCREAMING_SNAKE_CASE : Union[str, Any] = v.T # Block i, layer 1 (MLP). __SCREAMING_SNAKE_CASE : Any = tax_layer_norm_lookup(lowercase_ , lowercase_ , '''encoder''' , '''pre_mlp_layer_norm''' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = tax_mlp_lookup(lowercase_ , lowercase_ , '''encoder''' , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = layer_norm if split_mlp_wi: __SCREAMING_SNAKE_CASE : int = wi[0].T __SCREAMING_SNAKE_CASE : Dict = wi[1].T else: __SCREAMING_SNAKE_CASE : List[str] = wi.T __SCREAMING_SNAKE_CASE : Any = wo.T __SCREAMING_SNAKE_CASE : str = old[ '''encoder/relpos_bias/rel_embedding''' ].T __SCREAMING_SNAKE_CASE : Any = old['''encoder/encoder_norm/scale'''] if not is_encoder_only: # Decoder. for i in range(lowercase_ ): # Block i, layer 0 (Self Attention). __SCREAMING_SNAKE_CASE : Union[str, Any] = tax_layer_norm_lookup(lowercase_ , lowercase_ , '''decoder''' , '''pre_self_attention_layer_norm''' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = tax_attention_lookup(lowercase_ , lowercase_ , '''decoder''' , '''self_attention''' ) __SCREAMING_SNAKE_CASE : Dict = layer_norm __SCREAMING_SNAKE_CASE : Any = k.T __SCREAMING_SNAKE_CASE : List[str] = o.T __SCREAMING_SNAKE_CASE : Dict = q.T __SCREAMING_SNAKE_CASE : List[Any] = v.T # Block i, layer 1 (Cross Attention). __SCREAMING_SNAKE_CASE : Union[str, Any] = tax_layer_norm_lookup(lowercase_ , lowercase_ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = tax_attention_lookup(lowercase_ , lowercase_ , '''decoder''' , '''encoder_decoder_attention''' ) __SCREAMING_SNAKE_CASE : Optional[int] = layer_norm __SCREAMING_SNAKE_CASE : int = k.T __SCREAMING_SNAKE_CASE : Tuple = o.T __SCREAMING_SNAKE_CASE : Union[str, Any] = q.T __SCREAMING_SNAKE_CASE : str = v.T # Block i, layer 2 (MLP). __SCREAMING_SNAKE_CASE : Tuple = tax_layer_norm_lookup(lowercase_ , lowercase_ , '''decoder''' , '''pre_mlp_layer_norm''' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = tax_mlp_lookup(lowercase_ , lowercase_ , '''decoder''' , lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm if split_mlp_wi: __SCREAMING_SNAKE_CASE : Tuple = wi[0].T __SCREAMING_SNAKE_CASE : Optional[Any] = wi[1].T else: __SCREAMING_SNAKE_CASE : Union[str, Any] = wi.T __SCREAMING_SNAKE_CASE : List[str] = wo.T __SCREAMING_SNAKE_CASE : Dict = old['''decoder/decoder_norm/scale'''] __SCREAMING_SNAKE_CASE : List[str] = old[ '''decoder/relpos_bias/rel_embedding''' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: __SCREAMING_SNAKE_CASE : Dict = old['''decoder/logits_dense/kernel'''].T return new def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : bool ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: __SCREAMING_SNAKE_CASE : Tuple = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = state_dict['''shared.weight'''] return state_dict def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = checkpoints.load_tax_checkpoint(lowercase_ ) __SCREAMING_SNAKE_CASE : Any = convert_tax_to_pytorch(lowercase_ , num_layers=config.num_layers , is_encoder_only=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = make_state_dict(lowercase_ , lowercase_ ) model.load_state_dict(lowercase_ , strict=lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : bool = False ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = TaConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: __SCREAMING_SNAKE_CASE : int = TaEncoderModel(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Dict = TaForConditionalGeneration(lowercase_ ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase_ ) # Verify that we can load the checkpoint. model.from_pretrained(lowercase_ ) print('''Done''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) _lowerCamelCase = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = PegasusTokenizer lowerCamelCase__ = PegasusTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :Tuple ): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : List[Any] = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def SCREAMING_SNAKE_CASE_ ( self :Any , **_lowerCamelCase :Any ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Union[str, Any] ): return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = '''</s>''' __SCREAMING_SNAKE_CASE : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''</s>''' ) self.assertEqual(vocab_keys[-1] , '''v''' ) self.assertEqual(len(_lowerCamelCase ) , 1_1_0_3 ) def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(self.get_tokenizer().vocab_size , 1_1_0_3 ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Any = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] __SCREAMING_SNAKE_CASE : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[int] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __SCREAMING_SNAKE_CASE : int = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __SCREAMING_SNAKE_CASE : Dict = [2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __SCREAMING_SNAKE_CASE : int = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : str = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6_1_0_3 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_0_3 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_0_2_4 __SCREAMING_SNAKE_CASE : Dict = '''To ensure a smooth flow of bank resolutions.''' __SCREAMING_SNAKE_CASE : int = [4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = ['''This is going to be way too long.''' * 1_5_0, '''short example'''] __SCREAMING_SNAKE_CASE : Tuple = ['''not super long but more than 5 tokens''', '''tiny'''] __SCREAMING_SNAKE_CASE : Dict = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : List[str] = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1_0_2_4) assert batch.attention_mask.shape == (2, 1_0_2_4) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def SCREAMING_SNAKE_CASE_ ( self :str ): # fmt: off __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0_6, 1_3_0, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 5_4_1_8_9, 1_1_2_9, 1_1_1, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 9_1_1_4, 1_4_7_8_7, 1_2_1, 1_3_2_4_9, 1_5_8, 5_9_2, 9_5_6, 1_2_1, 1_4_6_2_1, 3_1_5_7_6, 1_4_3, 6_2_6_1_3, 1_0_8, 9_6_8_8, 9_3_0, 4_3_4_3_0, 1_1_5_6_2, 6_2_6_1_3, 3_0_4, 1_0_8, 1_1_4_4_3, 8_9_7, 1_0_8, 9_3_1_4, 1_7_4_1_5, 6_3_3_9_9, 1_0_8, 1_1_4_4_3, 7_6_1_4, 1_8_3_1_6, 1_1_8, 4_2_8_4, 7_1_4_8, 1_2_4_3_0, 1_4_3, 1_4_0_0, 2_5_7_0_3, 1_5_8, 1_1_1, 4_2_8_4, 7_1_4_8, 1_1_7_7_2, 1_4_3, 2_1_2_9_7, 1_0_6_4, 1_5_8, 1_2_2, 2_0_4, 3_5_0_6, 1_7_5_4, 1_1_3_3, 1_4_7_8_7, 1_5_8_1, 1_1_5, 3_3_2_2_4, 4_4_8_2, 1_1_1, 1_3_5_5, 1_1_0, 2_9_1_7_3, 3_1_7, 5_0_8_3_3, 1_0_8, 2_0_1_4_7, 9_4_6_6_5, 1_1_1, 7_7_1_9_8, 1_0_7, 1], [1_1_0, 6_2_6_1_3, 1_1_7, 6_3_8, 1_1_2, 1_1_3_3, 1_2_1, 2_0_0_9_8, 1_3_5_5, 7_9_0_5_0, 1_3_8_7_2, 1_3_5, 1_5_9_6, 5_3_5_4_1, 1_3_5_2, 1_4_1, 1_3_0_3_9, 5_5_4_2, 1_2_4, 3_0_2, 5_1_8, 1_1_1, 2_6_8, 2_9_5_6, 1_1_5, 1_4_9, 4_4_2_7, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_3_9, 1_2_3_5, 2_7_9_9, 1_8_2_8_9, 1_7_7_8_0, 2_0_4, 1_0_9, 9_4_7_4, 1_2_9_6, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = PegasusTokenizer lowerCamelCase__ = PegasusTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :Any ): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : Any = PegasusTokenizer(_lowerCamelCase , offset=0 , mask_token_sent=_lowerCamelCase , mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Any = self.tokenizer_class.from_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Dict = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] __SCREAMING_SNAKE_CASE : List[Any] = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : int = ['''This is going to be way too long.''' * 1_0_0_0, '''short example'''] __SCREAMING_SNAKE_CASE : int = ['''not super long but more than 5 tokens''', '''tiny'''] __SCREAMING_SNAKE_CASE : Dict = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : int = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4_0_9_6) assert batch.attention_mask.shape == (2, 4_0_9_6) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __SCREAMING_SNAKE_CASE : List[str] = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase , [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1] , )
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-base/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''align_text_model''' def __init__( self :Optional[Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :Optional[Any]=7_6_8 , _lowerCamelCase :Tuple=1_2 , _lowerCamelCase :Any=1_2 , _lowerCamelCase :Union[str, Any]=3_0_7_2 , _lowerCamelCase :Optional[Any]="gelu" , _lowerCamelCase :Optional[Any]=0.1 , _lowerCamelCase :Tuple=0.1 , _lowerCamelCase :Any=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :List[str]=0.0_2 , _lowerCamelCase :Any=1e-12 , _lowerCamelCase :Optional[int]=0 , _lowerCamelCase :Tuple="absolute" , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :Optional[int] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = vocab_size __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size __SCREAMING_SNAKE_CASE : int = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : int = intermediate_size __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings __SCREAMING_SNAKE_CASE : Tuple = type_vocab_size __SCREAMING_SNAKE_CASE : List[Any] = initializer_range __SCREAMING_SNAKE_CASE : int = layer_norm_eps __SCREAMING_SNAKE_CASE : str = position_embedding_type __SCREAMING_SNAKE_CASE : Tuple = use_cache __SCREAMING_SNAKE_CASE : Tuple = pad_token_id @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Optional[int] , _lowerCamelCase :Union[str, os.PathLike] , **_lowerCamelCase :int ): cls._set_token_in_kwargs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": __SCREAMING_SNAKE_CASE : Optional[int] = 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(_lowerCamelCase , **_lowerCamelCase ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''align_vision_model''' def __init__( self :Tuple , _lowerCamelCase :int = 3 , _lowerCamelCase :int = 6_0_0 , _lowerCamelCase :float = 2.0 , _lowerCamelCase :float = 3.1 , _lowerCamelCase :int = 8 , _lowerCamelCase :List[int] = [3, 3, 5, 3, 5, 5, 3] , _lowerCamelCase :List[int] = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , _lowerCamelCase :List[int] = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , _lowerCamelCase :List[int] = [] , _lowerCamelCase :List[int] = [1, 2, 2, 2, 1, 2, 1] , _lowerCamelCase :List[int] = [1, 2, 2, 3, 3, 4, 1] , _lowerCamelCase :List[int] = [1, 6, 6, 6, 6, 6, 6] , _lowerCamelCase :float = 0.2_5 , _lowerCamelCase :str = "swish" , _lowerCamelCase :int = 2_5_6_0 , _lowerCamelCase :str = "mean" , _lowerCamelCase :float = 0.0_2 , _lowerCamelCase :float = 0.0_0_1 , _lowerCamelCase :float = 0.9_9 , _lowerCamelCase :float = 0.2 , **_lowerCamelCase :List[Any] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = num_channels __SCREAMING_SNAKE_CASE : str = image_size __SCREAMING_SNAKE_CASE : Any = width_coefficient __SCREAMING_SNAKE_CASE : List[str] = depth_coefficient __SCREAMING_SNAKE_CASE : List[Any] = depth_divisor __SCREAMING_SNAKE_CASE : Optional[Any] = kernel_sizes __SCREAMING_SNAKE_CASE : Tuple = in_channels __SCREAMING_SNAKE_CASE : Optional[Any] = out_channels __SCREAMING_SNAKE_CASE : Optional[Any] = depthwise_padding __SCREAMING_SNAKE_CASE : Optional[int] = strides __SCREAMING_SNAKE_CASE : Tuple = num_block_repeats __SCREAMING_SNAKE_CASE : Union[str, Any] = expand_ratios __SCREAMING_SNAKE_CASE : str = squeeze_expansion_ratio __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = pooling_type __SCREAMING_SNAKE_CASE : Tuple = initializer_range __SCREAMING_SNAKE_CASE : List[str] = batch_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = batch_norm_momentum __SCREAMING_SNAKE_CASE : List[Any] = drop_connect_rate __SCREAMING_SNAKE_CASE : List[str] = sum(_lowerCamelCase ) * 4 @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Optional[Any] , _lowerCamelCase :Union[str, os.PathLike] , **_lowerCamelCase :Union[str, Any] ): cls._set_token_in_kwargs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": __SCREAMING_SNAKE_CASE : Optional[int] = 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(_lowerCamelCase , **_lowerCamelCase ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''align''' lowerCamelCase__ = True def __init__( self :Union[str, Any] , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[str]=6_4_0 , _lowerCamelCase :Any=1.0 , _lowerCamelCase :Dict=0.0_2 , **_lowerCamelCase :List[str] , ): super().__init__(**_lowerCamelCase ) if text_config is None: __SCREAMING_SNAKE_CASE : List[Any] = {} logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''' ) if vision_config is None: __SCREAMING_SNAKE_CASE : Tuple = {} logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''' ) __SCREAMING_SNAKE_CASE : Optional[int] = AlignTextConfig(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AlignVisionConfig(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = projection_dim __SCREAMING_SNAKE_CASE : Any = temperature_init_value __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range @classmethod def SCREAMING_SNAKE_CASE_ ( cls :str , _lowerCamelCase :AlignTextConfig , _lowerCamelCase :AlignVisionConfig , **_lowerCamelCase :Optional[int] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Optional[Any] = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE : str = self.text_config.to_dict() __SCREAMING_SNAKE_CASE : Optional[int] = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE : Dict = self.__class__.model_type return output
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''gpt_neox_japanese''' def __init__( self :Union[str, Any] , _lowerCamelCase :str=3_2_0_0_0 , _lowerCamelCase :Any=2_5_6_0 , _lowerCamelCase :Optional[int]=3_2 , _lowerCamelCase :Union[str, Any]=3_2 , _lowerCamelCase :Any=4 , _lowerCamelCase :int="gelu" , _lowerCamelCase :List[str]=1.0_0 , _lowerCamelCase :List[str]=1_0_0_0_0 , _lowerCamelCase :Any=2_0_4_8 , _lowerCamelCase :Optional[Any]=0.0_2 , _lowerCamelCase :List[Any]=1e-5 , _lowerCamelCase :str=True , _lowerCamelCase :Union[str, Any]=3_1_9_9_6 , _lowerCamelCase :int=3_1_9_9_9 , _lowerCamelCase :Optional[Any]=0.1 , _lowerCamelCase :Tuple=0.0 , **_lowerCamelCase :List[str] , ): super().__init__(bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = vocab_size __SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : str = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[int] = intermediate_multiple_size __SCREAMING_SNAKE_CASE : Any = hidden_act __SCREAMING_SNAKE_CASE : str = rotary_pct __SCREAMING_SNAKE_CASE : Optional[Any] = rotary_emb_base __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Any = layer_norm_eps __SCREAMING_SNAKE_CASE : Any = use_cache __SCREAMING_SNAKE_CASE : str = attention_dropout __SCREAMING_SNAKE_CASE : Dict = hidden_dropout
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" from math import pi, sqrt def lowerCAmelCase_ ( lowercase_ : float ): '''simple docstring''' if num <= 0: raise ValueError('''math domain error''' ) if num > 171.5: raise OverflowError('''math range error''' ) elif num - int(lowercase_ ) not in (0, 0.5): raise NotImplementedError('''num must be an integer or a half-integer''' ) elif num == 0.5: return sqrt(lowercase_ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def lowerCAmelCase_ ( ): '''simple docstring''' assert gamma(0.5 ) == sqrt(lowercase_ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowerCamelCase = 1.0 while num: _lowerCamelCase = float(input('''Gamma of: ''')) print(f'gamma({num}) = {gamma(num)}') print('''\nEnter 0 to exit...''')
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import re def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : bool , lowercase_ : str ): '''simple docstring''' try: __SCREAMING_SNAKE_CASE : Any = split_input(lowercase_ ) if upper: __SCREAMING_SNAKE_CASE : Dict = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __SCREAMING_SNAKE_CASE : Dict = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return to_simple_case(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' try: __SCREAMING_SNAKE_CASE : List[Any] = to_simple_case(lowercase_ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : bool ): '''simple docstring''' return to_complex_case(lowercase_ , lowercase_ , '''_''' ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : bool ): '''simple docstring''' return to_complex_case(lowercase_ , lowercase_ , '''-''' ) if __name__ == "__main__": __import__('''doctest''').testmod()
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Dict = '''ylacombe/bark-small''' __SCREAMING_SNAKE_CASE : str = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = '''en_speaker_1''' __SCREAMING_SNAKE_CASE : Union[str, Any] = '''This is a test string''' __SCREAMING_SNAKE_CASE : Dict = '''speaker_embeddings_path.json''' __SCREAMING_SNAKE_CASE : Optional[Any] = '''speaker_embeddings''' def SCREAMING_SNAKE_CASE_ ( self :Any , **_lowerCamelCase :Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = BarkProcessor(tokenizer=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : str = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : Tuple = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __SCREAMING_SNAKE_CASE : Optional[Any] = 3_5 __SCREAMING_SNAKE_CASE : List[Any] = 2 __SCREAMING_SNAKE_CASE : Any = 8 __SCREAMING_SNAKE_CASE : Dict = { '''semantic_prompt''': np.ones(_lowerCamelCase ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __SCREAMING_SNAKE_CASE : int = processor(text=self.input_string , voice_preset=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file __SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=self.input_string , voice_preset=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub __SCREAMING_SNAKE_CASE : int = processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Dict = BarkProcessor(tokenizer=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = processor(text=self.input_string ) __SCREAMING_SNAKE_CASE : int = tokenizer( self.input_string , padding='''max_length''' , max_length=2_5_6 , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class snake_case ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[str] = ort.SessionOptions() __SCREAMING_SNAKE_CASE : List[str] = False return options def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __SCREAMING_SNAKE_CASE : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy''' ) # using the PNDM scheduler by default __SCREAMING_SNAKE_CASE : Optional[int] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=_lowerCamelCase , feature_extractor=_lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = '''A red cat sitting on a park bench''' __SCREAMING_SNAKE_CASE : Optional[int] = np.random.RandomState(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , mask_image=_lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=1_5 , generator=_lowerCamelCase , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 1e-2
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _lowerCamelCase = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) __SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(_lowerCamelCase , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = generator.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = '''cyberpunk 2077''' __SCREAMING_SNAKE_CASE : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) __SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt=_lowerCamelCase , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' , ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : List[str] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __SCREAMING_SNAKE_CASE : List[str] = '''A painting of a squirrel eating a burger ''' __SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = pipe.text_to_image( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : Any = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : List[Any] = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __SCREAMING_SNAKE_CASE : str = pipe.image_variation(_lowerCamelCase , generator=_lowerCamelCase , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 lowerCamelCase__ = None def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : str=0.999 , lowercase_ : Optional[Any]="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(lowercase_ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowercase_ : int ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __SCREAMING_SNAKE_CASE : str = [] for i in range(lowercase_ ): __SCREAMING_SNAKE_CASE : int = i / num_diffusion_timesteps __SCREAMING_SNAKE_CASE : Dict = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowercase_ ) / alpha_bar_fn(lowercase_ ) , lowercase_ ) ) return torch.tensor(lowercase_ , dtype=torch.floataa ) class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :Optional[int] , _lowerCamelCase :int = 1_0_0_0 , _lowerCamelCase :str = "fixed_small_log" , _lowerCamelCase :bool = True , _lowerCamelCase :Optional[float] = 1.0 , _lowerCamelCase :str = "epsilon" , _lowerCamelCase :str = "squaredcos_cap_v2" , ): if beta_schedule != "squaredcos_cap_v2": raise ValueError('''UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'''' ) __SCREAMING_SNAKE_CASE : List[Any] = betas_for_alpha_bar(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = 1.0 - self.betas __SCREAMING_SNAKE_CASE : Dict = torch.cumprod(self.alphas , dim=0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(1.0 ) # standard deviation of the initial noise distribution __SCREAMING_SNAKE_CASE : Tuple = 1.0 # setable values __SCREAMING_SNAKE_CASE : Optional[int] = None __SCREAMING_SNAKE_CASE : Any = torch.from_numpy(np.arange(0 , _lowerCamelCase )[::-1].copy() ) __SCREAMING_SNAKE_CASE : Optional[Any] = variance_type def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[int] = None ): return sample def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Union[str, torch.device] = None ): __SCREAMING_SNAKE_CASE : Union[str, Any] = num_inference_steps __SCREAMING_SNAKE_CASE : Dict = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) __SCREAMING_SNAKE_CASE : Union[str, Any] = (np.arange(0 , _lowerCamelCase ) * step_ratio).round()[::-1].copy().astype(np.intaa ) __SCREAMING_SNAKE_CASE : Dict = torch.from_numpy(_lowerCamelCase ).to(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Any=None , _lowerCamelCase :Dict=None , _lowerCamelCase :str=None ): if prev_timestep is None: __SCREAMING_SNAKE_CASE : Tuple = t - 1 __SCREAMING_SNAKE_CASE : Tuple = self.alphas_cumprod[t] __SCREAMING_SNAKE_CASE : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __SCREAMING_SNAKE_CASE : int = 1 - alpha_prod_t __SCREAMING_SNAKE_CASE : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.betas[t] else: __SCREAMING_SNAKE_CASE : Tuple = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample __SCREAMING_SNAKE_CASE : Dict = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: __SCREAMING_SNAKE_CASE : Optional[int] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.log(torch.clamp(_lowerCamelCase , min=1e-20 ) ) __SCREAMING_SNAKE_CASE : Any = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler __SCREAMING_SNAKE_CASE : Union[str, Any] = variance.log() __SCREAMING_SNAKE_CASE : Union[str, Any] = beta.log() __SCREAMING_SNAKE_CASE : Dict = (predicted_variance + 1) / 2 __SCREAMING_SNAKE_CASE : Optional[Any] = frac * max_log + (1 - frac) * min_log return variance def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :int , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[int] = None , _lowerCamelCase :Tuple=None , _lowerCamelCase :bool = True , ): __SCREAMING_SNAKE_CASE : str = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.split(_lowerCamelCase , sample.shape[1] , dim=1 ) else: __SCREAMING_SNAKE_CASE : str = None # 1. compute alphas, betas if prev_timestep is None: __SCREAMING_SNAKE_CASE : int = t - 1 __SCREAMING_SNAKE_CASE : Tuple = self.alphas_cumprod[t] __SCREAMING_SNAKE_CASE : Optional[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __SCREAMING_SNAKE_CASE : int = 1 - alpha_prod_t __SCREAMING_SNAKE_CASE : Tuple = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __SCREAMING_SNAKE_CASE : str = self.betas[t] __SCREAMING_SNAKE_CASE : Any = self.alphas[t] else: __SCREAMING_SNAKE_CASE : Dict = 1 - alpha_prod_t / alpha_prod_t_prev __SCREAMING_SNAKE_CASE : Optional[Any] = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": __SCREAMING_SNAKE_CASE : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": __SCREAMING_SNAKE_CASE : List[Any] = model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' ''' for the UnCLIPScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: __SCREAMING_SNAKE_CASE : List[str] = torch.clamp( _lowerCamelCase , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __SCREAMING_SNAKE_CASE : Any = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t __SCREAMING_SNAKE_CASE : Optional[Any] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __SCREAMING_SNAKE_CASE : List[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 if t > 0: __SCREAMING_SNAKE_CASE : int = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=_lowerCamelCase , device=model_output.device ) __SCREAMING_SNAKE_CASE : Tuple = self._get_variance( _lowerCamelCase , predicted_variance=_lowerCamelCase , prev_timestep=_lowerCamelCase , ) if self.variance_type == "fixed_small_log": __SCREAMING_SNAKE_CASE : List[Any] = variance elif self.variance_type == "learned_range": __SCREAMING_SNAKE_CASE : Any = (0.5 * variance).exp() else: raise ValueError( f'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' ''' for the UnCLIPScheduler.''' ) __SCREAMING_SNAKE_CASE : int = variance * variance_noise __SCREAMING_SNAKE_CASE : str = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_lowerCamelCase , pred_original_sample=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :torch.IntTensor , ): # Make sure alphas_cumprod and timestep have same device and dtype as original_samples __SCREAMING_SNAKE_CASE : int = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) __SCREAMING_SNAKE_CASE : Optional[int] = timesteps.to(original_samples.device ) __SCREAMING_SNAKE_CASE : List[str] = alphas_cumprod[timesteps] ** 0.5 __SCREAMING_SNAKE_CASE : List[str] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): __SCREAMING_SNAKE_CASE : List[Any] = sqrt_alpha_prod.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : Dict = (1 - alphas_cumprod[timesteps]) ** 0.5 __SCREAMING_SNAKE_CASE : Union[str, Any] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): __SCREAMING_SNAKE_CASE : Optional[Any] = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : Tuple = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
674
"""simple docstring""" 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 lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = 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''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): lowerCamelCase__ = '''convnextv2''' def __init__( self :Optional[int] , _lowerCamelCase :str=3 , _lowerCamelCase :List[Any]=4 , _lowerCamelCase :Union[str, Any]=4 , _lowerCamelCase :int=None , _lowerCamelCase :str=None , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=0.0 , _lowerCamelCase :Optional[Any]=2_2_4 , _lowerCamelCase :Dict=None , _lowerCamelCase :List[Any]=None , **_lowerCamelCase :Optional[int] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : Optional[Any] = patch_size __SCREAMING_SNAKE_CASE : Dict = num_stages __SCREAMING_SNAKE_CASE : List[str] = [9_6, 1_9_2, 3_8_4, 7_6_8] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE : Dict = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Dict = layer_norm_eps __SCREAMING_SNAKE_CASE : int = drop_path_rate __SCREAMING_SNAKE_CASE : int = image_size __SCREAMING_SNAKE_CASE : List[str] = ['''stem'''] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names )
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class snake_case : lowerCamelCase__ = None lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = True lowerCamelCase__ = None lowerCamelCase__ = 1 lowerCamelCase__ = None lowerCamelCase__ = False lowerCamelCase__ = None lowerCamelCase__ = None def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return self.__class__(**{k: copy.deepcopy(_lowerCamelCase ) for k, v in self.__dict__.items()} )
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right _lowerCamelCase = 25_00_04 _lowerCamelCase = 25_00_20 @require_sentencepiece @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = MBartTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :str ): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : Optional[int] = MBartTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MBartTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = 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 [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def SCREAMING_SNAKE_CASE_ ( self :str ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __SCREAMING_SNAKE_CASE : List[Any] = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = tokenizer_p.save_pretrained(_lowerCamelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE : str = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(_lowerCamelCase , _lowerCamelCase ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase , _lowerCamelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(_lowerCamelCase ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : int = tokenizer_r.save_pretrained(_lowerCamelCase , legacy_format=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_p.save_pretrained(_lowerCamelCase ) # Checks it save with the same files self.assertSequenceEqual(_lowerCamelCase , _lowerCamelCase ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase , _lowerCamelCase ) ) shutil.rmtree(_lowerCamelCase ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE : List[Any] = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : Any = tokenizer_r.save_pretrained(_lowerCamelCase , legacy_format=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.save_pretrained(_lowerCamelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_p.from_pretrained(_lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCamelCase , _lowerCamelCase ) ) shutil.rmtree(_lowerCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class snake_case ( unittest.TestCase ): lowerCamelCase__ = '''facebook/mbart-large-en-ro''' lowerCamelCase__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] lowerCamelCase__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] lowerCamelCase__ = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :int ): __SCREAMING_SNAKE_CASE : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en_XX''' , tgt_lang='''ro_RO''' ) __SCREAMING_SNAKE_CASE : Dict = 1 return cls def SCREAMING_SNAKE_CASE_ ( self :str ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ar_AR'''] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''en_EN'''] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ro_RO'''] , 2_5_0_0_2_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Any = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.assertIn(_lowerCamelCase , self.tokenizer.all_special_ids ) __SCREAMING_SNAKE_CASE : str = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] __SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Dict = ['''this is gunna be a long sentence ''' * 2_0] assert isinstance(src_text[0] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = 1_0 __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(_lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _lowerCamelCase ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = MBartTokenizer.from_pretrained(_lowerCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _lowerCamelCase ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Any = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : int = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _lowerCamelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(self.src_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=3 , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : int = self.tokenizer( text_target=self.tgt_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=1_0 , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Optional[int] = targets['''input_ids'''] __SCREAMING_SNAKE_CASE : List[str] = shift_tokens_right(_lowerCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''ar_AR''' ) self.assertEqual( nested_simplify(_lowerCamelCase ) , { # A, test, EOS, en_XX '''input_ids''': [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 2_5_0_0_0_1, } , )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 _lowerCamelCase = 0B1011_0011_1110_1100_1001_0000_0111_1011_1011_0001_1001_1110 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 _lowerCamelCase = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class snake_case : def __init__( self :Dict ): __SCREAMING_SNAKE_CASE : Any = WATERMARK_BITS __SCREAMING_SNAKE_CASE : List[Any] = WatermarkEncoder() self.encoder.set_watermark('''bits''' , self.watermark ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :torch.FloatTensor ): # can't encode images that are smaller than 256 if images.shape[-1] < 2_5_6: return images __SCREAMING_SNAKE_CASE : Dict = (2_5_5 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __SCREAMING_SNAKE_CASE : Optional[Any] = [self.encoder.encode(_lowerCamelCase , '''dwtDct''' ) for image in images] __SCREAMING_SNAKE_CASE : Dict = torch.from_numpy(np.array(_lowerCamelCase ) ).permute(0 , 3 , 1 , 2 ) __SCREAMING_SNAKE_CASE : int = torch.clamp(2 * (images / 2_5_5 - 0.5) , min=-1.0 , max=1.0 ) return images
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" _lowerCamelCase = '''Alexander Joslin''' import operator as op from .stack import Stack def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub} __SCREAMING_SNAKE_CASE : Stack[int] = Stack() __SCREAMING_SNAKE_CASE : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowercase_ ) ) elif i in operators: # RULE 2 operator_stack.push(lowercase_ ) elif i == ")": # RULE 4 __SCREAMING_SNAKE_CASE : Any = operator_stack.peek() operator_stack.pop() __SCREAMING_SNAKE_CASE : List[Any] = operand_stack.peek() operand_stack.pop() __SCREAMING_SNAKE_CASE : Union[str, Any] = operand_stack.peek() operand_stack.pop() __SCREAMING_SNAKE_CASE : List[Any] = operators[opr](lowercase_ , lowercase_ ) operand_stack.push(lowercase_ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": _lowerCamelCase = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path _lowerCamelCase = [ {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.de'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.en'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.fr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.frr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.it'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.simple'''}, {'''dataset''': '''snli''', '''config_name''': '''plain_text'''}, {'''dataset''': '''eli5''', '''config_name''': '''LFQA_reddit'''}, {'''dataset''': '''wiki40b''', '''config_name''': '''en'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.compressed'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.no_index'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.multiset.no_index'''}, {'''dataset''': '''natural_questions''', '''config_name''': '''default'''}, ] def lowerCAmelCase_ ( lowercase_ : int=True ): '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=__UpperCAmelCase ) ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = None lowerCamelCase__ = None def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :int , _lowerCamelCase :Tuple ): with TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE : Tuple = dataset_module_factory(_lowerCamelCase , cache_dir=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = import_main_class(dataset_module.module_path , dataset=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : DatasetBuilder = builder_cls( cache_dir=_lowerCamelCase , config_name=_lowerCamelCase , hash=dataset_module.hash , ) __SCREAMING_SNAKE_CASE : List[str] = '''/'''.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=_lowerCamelCase ).replace(os.sep , '''/''' ), config.DATASET_INFO_FILENAME, ] ) __SCREAMING_SNAKE_CASE : List[str] = cached_path(_lowerCamelCase , cache_dir=_lowerCamelCase ) self.assertTrue(os.path.exists(_lowerCamelCase ) ) @pytest.mark.integration def lowerCAmelCase_ ( lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = tmp_path_factory.mktemp('''test_hf_gcp''' ) / '''test_wikipedia_simple''' __SCREAMING_SNAKE_CASE : Dict = dataset_module_factory('''wikipedia''' , cache_dir=lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = import_main_class(dataset_module.module_path ) __SCREAMING_SNAKE_CASE : DatasetBuilder = builder_cls( cache_dir=lowercase_ , config_name='''20220301.frr''' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam __SCREAMING_SNAKE_CASE : Optional[Any] = None builder_instance.download_and_prepare() __SCREAMING_SNAKE_CASE : Union[str, Any] = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = dataset_module_factory('''wikipedia''' , cache_dir=lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = import_main_class(dataset_module.module_path , dataset=lowercase_ ) __SCREAMING_SNAKE_CASE : DatasetBuilder = builder_cls( cache_dir=lowercase_ , config_name='''20220301.frr''' , hash=dataset_module.hash , ) __SCREAMING_SNAKE_CASE : List[Any] = builder_instance.as_streaming_dataset() assert ds assert isinstance(lowercase_ , lowercase_ ) assert "train" in ds assert isinstance(ds['''train'''] , lowercase_ ) assert next(iter(ds['''train'''] ) )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : list[list[float]] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[list[float]] = [] for data in source_data: for i, el in enumerate(lowercase_ ): if len(lowercase_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(lowercase_ ) ) return data_lists def lowerCAmelCase_ ( lowercase_ : list[list[float]] , lowercase_ : list[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[list[float]] = [] for dlist, weight in zip(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : int = min(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = max(lowercase_ ) __SCREAMING_SNAKE_CASE : list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: __SCREAMING_SNAKE_CASE : Any = F'''Invalid weight of {weight:f} provided''' raise ValueError(lowercase_ ) score_lists.append(lowercase_ ) return score_lists def lowerCAmelCase_ ( lowercase_ : list[list[float]] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = final_scores[j] + ele return final_scores def lowerCAmelCase_ ( lowercase_ : list[list[float]] , lowercase_ : list[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = get_data(lowercase_ ) __SCREAMING_SNAKE_CASE : str = calculate_each_score(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Any = generate_final_scores(lowercase_ ) # append scores to source data for i, ele in enumerate(lowercase_ ): source_data[i].append(lowercase_ ) return source_data
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml _lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase_ : bool , lowercase_ : bool ): '''simple docstring''' def run_func(lowercase_ : List[str] ): @wraps(lowercase_ ) def run_in_eager_mode(*lowercase_ : Optional[Any] , **lowercase_ : List[Any] ): return func(*lowercase_ , **lowercase_ ) @wraps(lowercase_ ) @tf.function(experimental_compile=lowercase_ ) def run_in_graph_mode(*lowercase_ : List[str] , **lowercase_ : Optional[Any] ): return func(*lowercase_ , **lowercase_ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.''' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = random.Random() __SCREAMING_SNAKE_CASE : Any = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowercase_ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = "TensorFlow" @property def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return tf.__version__ def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): # initialize GPU on separate process __SCREAMING_SNAKE_CASE : Tuple = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) __SCREAMING_SNAKE_CASE : Tuple = self._prepare_inference_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_speed(_inference ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) __SCREAMING_SNAKE_CASE : Any = self._prepare_train_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_speed(_train ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): # initialize GPU on separate process if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = self._prepare_inference_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_memory(_inference ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) __SCREAMING_SNAKE_CASE : str = self._prepare_train_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_memory(_train ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) __SCREAMING_SNAKE_CASE : Optional[int] = ( hasattr(_lowerCamelCase , '''architectures''' ) and isinstance(config.architectures , _lowerCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __SCREAMING_SNAKE_CASE : Optional[Any] = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model __SCREAMING_SNAKE_CASE : Tuple = __import__('''transformers''' , fromlist=[model_class] ) __SCREAMING_SNAKE_CASE : Any = getattr(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model_cls(_lowerCamelCase ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = TF_MODEL_MAPPING[config.__class__](_lowerCamelCase ) # encoder-decoder has vocab size saved differently __SCREAMING_SNAKE_CASE : Any = config.vocab_size if hasattr(_lowerCamelCase , '''vocab_size''' ) else config.encoder.vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = random_input_ids(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_lowerCamelCase , decoder_input_ids=_lowerCamelCase , training=_lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_lowerCamelCase , training=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Dict = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.''' ) if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) __SCREAMING_SNAKE_CASE : Dict = ( hasattr(_lowerCamelCase , '''architectures''' ) and isinstance(config.architectures , _lowerCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __SCREAMING_SNAKE_CASE : List[str] = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model __SCREAMING_SNAKE_CASE : str = __import__('''transformers''' , fromlist=[model_class] ) __SCREAMING_SNAKE_CASE : Dict = getattr(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model_cls(_lowerCamelCase ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: __SCREAMING_SNAKE_CASE : str = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_lowerCamelCase ) # encoder-decoder has vocab size saved differently __SCREAMING_SNAKE_CASE : Optional[int] = config.vocab_size if hasattr(_lowerCamelCase , '''vocab_size''' ) else config.encoder.vocab_size __SCREAMING_SNAKE_CASE : Optional[Any] = random_input_ids(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): __SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , decoder_input_ids=_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Dict = tf.gradients(_lowerCamelCase , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Any = tf.gradients(_lowerCamelCase , model.trainable_variables ) return gradients __SCREAMING_SNAKE_CASE : Tuple = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Dict ): with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation''' ) timeit.repeat(_lowerCamelCase , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average __SCREAMING_SNAKE_CASE : Optional[int] = timeit.repeat( _lowerCamelCase , repeat=self.args.repeat , number=1_0 , ) return min(_lowerCamelCase ) / 1_0.0 except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Callable[[], None] ): logger.info( '''Note that TensorFlow allocates more memory than ''' '''it might need to speed up computation. ''' '''The memory reported here corresponds to the memory ''' '''reported by `nvidia-smi`, which can vary depending ''' '''on total available memory on the GPU that is used.''' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory''' ''' consumption line by line.''' ) __SCREAMING_SNAKE_CASE : List[str] = start_memory_tracing('''transformers''' ) if self.args.is_tpu: # tpu raise NotImplementedError( '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking''' ''' with `args.memory=False`''' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( '''py3nvml not installed, we won\'t log GPU memory usage. ''' '''Install py3nvml (pip install py3nvml) to log information about GPU.''' ) __SCREAMING_SNAKE_CASE : Any = '''N/A''' else: logger.info( '''Measuring total GPU usage on GPU device. Make sure to not have additional processes''' ''' running on the same GPU.''' ) # init nvml nvml.nvmlInit() func() __SCREAMING_SNAKE_CASE : Any = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) __SCREAMING_SNAKE_CASE : Optional[int] = nvml.nvmlDeviceGetMemoryInfo(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = meminfo.used __SCREAMING_SNAKE_CASE : Optional[int] = Memory(_lowerCamelCase ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in''' ''' TensorFlow.''' ) __SCREAMING_SNAKE_CASE : Any = None else: __SCREAMING_SNAKE_CASE : List[str] = measure_peak_memory_cpu(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = Memory(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else memory_bytes if self.args.trace_memory_line_by_line: __SCREAMING_SNAKE_CASE : List[str] = stop_memory_tracing(_lowerCamelCase ) if memory is None: __SCREAMING_SNAKE_CASE : int = summary.total else: __SCREAMING_SNAKE_CASE : Union[str, Any] = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) return "N/A", None
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _lowerCamelCase = abspath(join(dirname(dirname(dirname(__file__))), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' from transformers.testing_utils import pytest_terminal_summary_main __SCREAMING_SNAKE_CASE : int = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ )
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''instructblip_vision_model''' def __init__( self :Any , _lowerCamelCase :Dict=1_4_0_8 , _lowerCamelCase :Dict=6_1_4_4 , _lowerCamelCase :Any=3_9 , _lowerCamelCase :Dict=1_6 , _lowerCamelCase :Optional[Any]=2_2_4 , _lowerCamelCase :Optional[Any]=1_4 , _lowerCamelCase :List[str]="gelu" , _lowerCamelCase :List[Any]=1e-6 , _lowerCamelCase :Optional[Any]=0.0 , _lowerCamelCase :List[Any]=1e-10 , _lowerCamelCase :Tuple=True , **_lowerCamelCase :Any , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers __SCREAMING_SNAKE_CASE : str = num_attention_heads __SCREAMING_SNAKE_CASE : str = patch_size __SCREAMING_SNAKE_CASE : str = image_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : Any = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm_eps __SCREAMING_SNAKE_CASE : int = hidden_act __SCREAMING_SNAKE_CASE : Optional[Any] = qkv_bias @classmethod def SCREAMING_SNAKE_CASE_ ( cls :List[Any] , _lowerCamelCase :Union[str, os.PathLike] , **_lowerCamelCase :List[Any] ): cls._set_token_in_kwargs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": __SCREAMING_SNAKE_CASE : Union[str, 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(_lowerCamelCase , **_lowerCamelCase ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''instructblip_qformer''' def __init__( self :Optional[int] , _lowerCamelCase :Union[str, Any]=3_0_5_2_2 , _lowerCamelCase :List[Any]=7_6_8 , _lowerCamelCase :Dict=1_2 , _lowerCamelCase :Optional[int]=1_2 , _lowerCamelCase :int=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :Optional[int]=0.1 , _lowerCamelCase :str=0.1 , _lowerCamelCase :Optional[Any]=5_1_2 , _lowerCamelCase :Tuple=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :Union[str, Any]=0 , _lowerCamelCase :Tuple="absolute" , _lowerCamelCase :Any=2 , _lowerCamelCase :int=1_4_0_8 , **_lowerCamelCase :str , ): super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = vocab_size __SCREAMING_SNAKE_CASE : str = hidden_size __SCREAMING_SNAKE_CASE : int = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = initializer_range __SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps __SCREAMING_SNAKE_CASE : List[str] = position_embedding_type __SCREAMING_SNAKE_CASE : str = cross_attention_frequency __SCREAMING_SNAKE_CASE : Optional[int] = encoder_hidden_size @classmethod def SCREAMING_SNAKE_CASE_ ( cls :str , _lowerCamelCase :Union[str, os.PathLike] , **_lowerCamelCase :Optional[int] ): cls._set_token_in_kwargs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": __SCREAMING_SNAKE_CASE : Dict = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_lowerCamelCase , **_lowerCamelCase ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''instructblip''' lowerCamelCase__ = True def __init__( self :Union[str, Any] , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Any=None , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Union[str, Any]=3_2 , **_lowerCamelCase :Dict ): super().__init__(**_lowerCamelCase ) if vision_config is None: __SCREAMING_SNAKE_CASE : int = {} logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''' ) if qformer_config is None: __SCREAMING_SNAKE_CASE : List[str] = {} logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''' ) if text_config is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = InstructBlipVisionConfig(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = InstructBlipQFormerConfig(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' __SCREAMING_SNAKE_CASE : List[Any] = CONFIG_MAPPING[text_model_type](**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.text_config.tie_word_embeddings __SCREAMING_SNAKE_CASE : Dict = self.text_config.is_encoder_decoder __SCREAMING_SNAKE_CASE : Optional[Any] = num_query_tokens __SCREAMING_SNAKE_CASE : Optional[int] = self.vision_config.hidden_size __SCREAMING_SNAKE_CASE : Dict = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __SCREAMING_SNAKE_CASE : Optional[int] = 1.0 __SCREAMING_SNAKE_CASE : List[str] = 0.0_2 @classmethod def SCREAMING_SNAKE_CASE_ ( cls :int , _lowerCamelCase :InstructBlipVisionConfig , _lowerCamelCase :InstructBlipQFormerConfig , _lowerCamelCase :PretrainedConfig , **_lowerCamelCase :Union[str, Any] , ): return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_lowerCamelCase , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE : Optional[int] = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE : Optional[Any] = self.qformer_config.to_dict() __SCREAMING_SNAKE_CASE : List[str] = self.text_config.to_dict() __SCREAMING_SNAKE_CASE : Dict = self.__class__.model_type return output
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import pprint import requests _lowerCamelCase = '''https://zenquotes.io/api''' def lowerCAmelCase_ ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def lowerCAmelCase_ ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": _lowerCamelCase = random_quotes() pprint.pprint(response)
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } _lowerCamelCase = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : Any ): '''simple docstring''' for attribute in key.split('''.''' ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __SCREAMING_SNAKE_CASE : int = '''lm_head''' __SCREAMING_SNAKE_CASE : Optional[Any] = getattr(lowercase_ , lowercase_ ) if weight_type is not None: __SCREAMING_SNAKE_CASE : Any = getattr(lowercase_ , lowercase_ ).shape else: __SCREAMING_SNAKE_CASE : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": __SCREAMING_SNAKE_CASE : Dict = value elif weight_type == "weight_g": __SCREAMING_SNAKE_CASE : Optional[Any] = value elif weight_type == "weight_v": __SCREAMING_SNAKE_CASE : str = value elif weight_type == "bias": __SCREAMING_SNAKE_CASE : List[Any] = value else: __SCREAMING_SNAKE_CASE : int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : List[str] , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Tuple = fairseq_model.state_dict() __SCREAMING_SNAKE_CASE : Optional[int] = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __SCREAMING_SNAKE_CASE : List[str] = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == '''group''' , ) __SCREAMING_SNAKE_CASE : Any = True else: for key, mapped_key in MAPPING.items(): __SCREAMING_SNAKE_CASE : Optional[Any] = '''unispeech.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __SCREAMING_SNAKE_CASE : Dict = True if "*" in mapped_key: __SCREAMING_SNAKE_CASE : Tuple = name.split(lowercase_ )[0].split('''.''' )[-2] __SCREAMING_SNAKE_CASE : Optional[int] = mapped_key.replace('''*''' , lowercase_ ) if "weight_g" in name: __SCREAMING_SNAKE_CASE : Dict = '''weight_g''' elif "weight_v" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = '''weight_v''' elif "bias" in name: __SCREAMING_SNAKE_CASE : int = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __SCREAMING_SNAKE_CASE : Dict = '''weight''' else: __SCREAMING_SNAKE_CASE : Tuple = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : str , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = full_name.split('''conv_layers.''' )[-1] __SCREAMING_SNAKE_CASE : Tuple = name.split('''.''' ) __SCREAMING_SNAKE_CASE : List[Any] = int(items[0] ) __SCREAMING_SNAKE_CASE : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : str = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) __SCREAMING_SNAKE_CASE : 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.''' ) __SCREAMING_SNAKE_CASE : Optional[int] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase_ ) @torch.no_grad() def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : Union[str, Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=True ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = UniSpeechConfig.from_pretrained(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Tuple = UniSpeechConfig() if is_finetuned: if dict_path: __SCREAMING_SNAKE_CASE : Tuple = Dictionary.load_from_json(lowercase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __SCREAMING_SNAKE_CASE : List[str] = target_dict.pad_index __SCREAMING_SNAKE_CASE : Dict = target_dict.bos_index __SCREAMING_SNAKE_CASE : Optional[Any] = target_dict.eos_index __SCREAMING_SNAKE_CASE : List[Any] = len(target_dict.symbols ) __SCREAMING_SNAKE_CASE : List[str] = os.path.join(lowercase_ , '''vocab.json''' ) if not os.path.isdir(lowercase_ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowercase_ ) ) return os.makedirs(lowercase_ , exist_ok=lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = target_dict.indices # fairseq has the <pad> and <s> switched __SCREAMING_SNAKE_CASE : List[Any] = 42 __SCREAMING_SNAKE_CASE : Tuple = 43 with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = WavaVecaPhonemeCTCTokenizer( lowercase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=lowercase_ , ) __SCREAMING_SNAKE_CASE : str = True if config.feat_extract_norm == '''layer''' else False __SCREAMING_SNAKE_CASE : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowercase_ , return_attention_mask=lowercase_ , ) __SCREAMING_SNAKE_CASE : Tuple = WavaVecaProcessor(feature_extractor=lowercase_ , tokenizer=lowercase_ ) processor.save_pretrained(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = UniSpeechForCTC(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = UniSpeechForPreTraining(lowercase_ ) if is_finetuned: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] ), '''w2v_path''': checkpoint_path} ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __SCREAMING_SNAKE_CASE : Optional[Any] = model[0].eval() recursively_load_weights(lowercase_ , lowercase_ , lowercase_ ) hf_unispeech.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) _lowerCamelCase = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" import os def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = os.path.join(os.path.dirname(lowercase_ ) , '''num.txt''' ) with open(lowercase_ ) as file_hand: return str(sum(int(lowercase_ ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" from __future__ import annotations from random import random from typing import Generic, TypeVar _lowerCamelCase = TypeVar('''KT''') _lowerCamelCase = TypeVar('''VT''') class snake_case ( Generic[KT, VT] ): def __init__( self :int , _lowerCamelCase :KT | str = "root" , _lowerCamelCase :VT | None = None ): __SCREAMING_SNAKE_CASE : List[Any] = key __SCREAMING_SNAKE_CASE : Optional[Any] = value __SCREAMING_SNAKE_CASE : list[Node[KT, VT]] = [] def __repr__( self :Dict ): return f'''Node({self.key}: {self.value})''' @property def SCREAMING_SNAKE_CASE_ ( self :int ): return len(self.forward ) class snake_case ( Generic[KT, VT] ): def __init__( self :Optional[int] , _lowerCamelCase :float = 0.5 , _lowerCamelCase :int = 1_6 ): __SCREAMING_SNAKE_CASE : Node[KT, VT] = Node[KT, VT]() __SCREAMING_SNAKE_CASE : Dict = 0 __SCREAMING_SNAKE_CASE : str = p __SCREAMING_SNAKE_CASE : List[str] = max_level def __str__( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[int] = list(self ) if len(_lowerCamelCase ) == 0: return f'''SkipList(level={self.level})''' __SCREAMING_SNAKE_CASE : Any = max((len(str(_lowerCamelCase ) ) for item in items) , default=4 ) __SCREAMING_SNAKE_CASE : List[Any] = max(_lowerCamelCase , 4 ) + 4 __SCREAMING_SNAKE_CASE : Tuple = self.head __SCREAMING_SNAKE_CASE : List[str] = [] __SCREAMING_SNAKE_CASE : List[Any] = node.forward.copy() lines.append(f'''[{node.key}]'''.ljust(_lowerCamelCase , '''-''' ) + '''* ''' * len(_lowerCamelCase ) ) lines.append(''' ''' * label_size + '''| ''' * len(_lowerCamelCase ) ) while len(node.forward ) != 0: __SCREAMING_SNAKE_CASE : List[Any] = node.forward[0] lines.append( f'''[{node.key}]'''.ljust(_lowerCamelCase , '''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[str] = node.forward lines.append('''None'''.ljust(_lowerCamelCase ) + '''* ''' * len(_lowerCamelCase ) ) return f'''SkipList(level={self.level})\n''' + "\n".join(_lowerCamelCase ) def __iter__( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.head while len(node.forward ) != 0: yield node.forward[0].key __SCREAMING_SNAKE_CASE : List[str] = node.forward[0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Any = 1 while random() < self.p and level < self.max_level: level += 1 return level def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : List[str] = [] __SCREAMING_SNAKE_CASE : Any = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: __SCREAMING_SNAKE_CASE : Union[str, Any] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_lowerCamelCase ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :KT ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = self._locate_node(_lowerCamelCase ) if node is not None: for i, update_node in enumerate(_lowerCamelCase ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: __SCREAMING_SNAKE_CASE : List[str] = node.forward[i] else: __SCREAMING_SNAKE_CASE : int = update_node.forward[:i] def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :KT , _lowerCamelCase :VT ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self._locate_node(_lowerCamelCase ) if node is not None: __SCREAMING_SNAKE_CASE : List[str] = value else: __SCREAMING_SNAKE_CASE : str = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _lowerCamelCase ): update_vector.append(self.head ) __SCREAMING_SNAKE_CASE : List[Any] = level __SCREAMING_SNAKE_CASE : Tuple = Node(_lowerCamelCase , _lowerCamelCase ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : str = new_node def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :VT ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self._locate_node(_lowerCamelCase ) if node is not None: return node.value return None def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = SkipList() skip_list.insert('''Key1''' , 3 ) skip_list.insert('''Key2''' , 12 ) skip_list.insert('''Key3''' , 41 ) skip_list.insert('''Key4''' , -19 ) __SCREAMING_SNAKE_CASE : int = skip_list.head __SCREAMING_SNAKE_CASE : Optional[int] = {} while node.level != 0: __SCREAMING_SNAKE_CASE : str = node.forward[0] __SCREAMING_SNAKE_CASE : List[str] = node.value assert len(lowercase_ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = SkipList() skip_list.insert('''Key1''' , 10 ) skip_list.insert('''Key1''' , 12 ) skip_list.insert('''Key5''' , 7 ) skip_list.insert('''Key7''' , 10 ) skip_list.insert('''Key10''' , 5 ) skip_list.insert('''Key7''' , 7 ) skip_list.insert('''Key5''' , 5 ) skip_list.insert('''Key10''' , 10 ) __SCREAMING_SNAKE_CASE : int = skip_list.head __SCREAMING_SNAKE_CASE : int = {} while node.level != 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = node.forward[0] __SCREAMING_SNAKE_CASE : Dict = node.value if len(lowercase_ ) != 4: print() assert len(lowercase_ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = SkipList() assert skip_list.find('''Some key''' ) is None def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = SkipList() skip_list.insert('''Key2''' , 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''' , 10 ) skip_list.insert('''Key2''' , 8 ) skip_list.insert('''V''' , 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 142 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''X''' ) def traverse_keys(lowercase_ : List[Any] ): yield node.key for forward_node in node.forward: yield from traverse_keys(lowercase_ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowerCAmelCase_ ( ): '''simple docstring''' def is_sorted(lowercase_ : str ): return all(next_item >= item for item, next_item in zip(lowercase_ , lst[1:] ) ) __SCREAMING_SNAKE_CASE : str = SkipList() for i in range(10 ): skip_list.insert(lowercase_ , lowercase_ ) assert is_sorted(list(lowercase_ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(lowercase_ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(lowercase_ ) ) def lowerCAmelCase_ ( ): '''simple docstring''' for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = SkipList() skip_list.insert(2 , '''2''' ) skip_list.insert(4 , '''4''' ) skip_list.insert(6 , '''4''' ) skip_list.insert(4 , '''5''' ) skip_list.insert(8 , '''4''' ) skip_list.insert(9 , '''4''' ) skip_list.delete(4 ) print(lowercase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 50 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration SCREAMING_SNAKE_CASE__ : Optional[Any] = pytest.mark.integration SCREAMING_SNAKE_CASE__ : Dict = {"""comet"""} SCREAMING_SNAKE_CASE__ : Dict = importlib.util.find_spec("""fairseq""") is not None SCREAMING_SNAKE_CASE__ : Tuple = {"""code_eval"""} SCREAMING_SNAKE_CASE__ : List[Any] = os.name == """nt""" SCREAMING_SNAKE_CASE__ : Optional[int] = {"""bertscore""", """frugalscore""", """perplexity"""} SCREAMING_SNAKE_CASE__ : Dict = importlib.util.find_spec("""transformers""") is not None def __lowercase ( snake_case ): """simple docstring""" @wraps(snake_case ) def wrapper(self, snake_case ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self, snake_case ) return wrapper def __lowercase ( snake_case ): """simple docstring""" @wraps(snake_case ) def wrapper(self, snake_case ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self, snake_case ) return wrapper def __lowercase ( snake_case ): """simple docstring""" @wraps(snake_case ) def wrapper(self, snake_case ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self, snake_case ) return wrapper def __lowercase ( ): """simple docstring""" __magic_name__ :Optional[int] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCamelCase , lowerCamelCase , lowerCamelCase ) @local class lowerCamelCase_ ( parameterized.TestCase ): a__ = {} a__ = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Tuple = '''[...]''' __magic_name__ :int = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , __lowerCAmelCase ) ).module_path ) __magic_name__ :Any = datasets.load.import_main_class(metric_module.__name__ , dataset=__lowerCAmelCase ) # check parameters __magic_name__ :Tuple = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__lowerCAmelCase , metric_module.__name__ ): with self.use_local_metrics(): try: __magic_name__ :Any = doctest.testmod(__lowerCAmelCase , verbose=__lowerCAmelCase , raise_on_error=__lowerCAmelCase ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Union[str, Any] = '''[...]''' __magic_name__ :Dict = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , __lowerCAmelCase ) ).module_path ) # run doctest with self.use_local_metrics(): __magic_name__ :int = doctest.testmod(__lowerCAmelCase , verbose=__lowerCAmelCase , raise_on_error=__lowerCAmelCase ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def A ( self , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowerCAmelCase ): yield else: yield @contextmanager def A ( self ): """simple docstring""" def load_local_metric(__lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ): return load_metric(os.path.join('''metrics''' , __lowerCAmelCase ) , *__lowerCAmelCase , **__lowerCAmelCase ) with patch('''datasets.load_metric''' ) as mock_load_metric: __magic_name__ :Dict = load_local_metric yield @classmethod def A ( cls , __lowerCAmelCase ): """simple docstring""" def wrapper(__lowerCAmelCase ): __magic_name__ :Union[str, Any] = contextmanager(__lowerCAmelCase ) __magic_name__ :Dict = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def __lowercase ( snake_case ): """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''', '''''', '''''' ) # handle pytest cli flags class lowerCamelCase_ ( lowerCamelCase ): def A ( self , __lowerCAmelCase ): """simple docstring""" assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: __magic_name__ :List[Any] = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def __lowercase ( snake_case ): """simple docstring""" import torch def bert_cos_score_idf(snake_case, snake_case, *snake_case, **snake_case ): return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: __magic_name__ :Optional[int] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def __lowercase ( snake_case ): """simple docstring""" def load_from_checkpoint(snake_case ): class lowerCamelCase_ : def A ( self , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" assert len(__lowerCAmelCase ) == 2 __magic_name__ :int = [0.19, 0.92] return scores, sum(__lowerCAmelCase ) / len(__lowerCAmelCase ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: __magic_name__ :Optional[int] = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: __magic_name__ :Any = load_from_checkpoint yield def __lowercase ( ): """simple docstring""" __magic_name__ :Optional[int] = load_metric(os.path.join('''metrics''', '''seqeval''' ) ) __magic_name__ :List[str] = '''ERROR''' __magic_name__ :str = f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(snake_case, match=re.escape(snake_case ) ): metric.compute(predictions=[], references=[], scheme=snake_case )
0
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
0
def _A ( _lowercase = 10**9 ) -> int: """simple docstring""" __UpperCamelCase = 1 __UpperCamelCase = 2 __UpperCamelCase = 0 __UpperCamelCase = 0 __UpperCamelCase = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value __UpperCamelCase = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"""{solution() = }""")
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { """configuration_roberta""": ["""ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RobertaConfig""", """RobertaOnnxConfig"""], """tokenization_roberta""": ["""RobertaTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ["""RobertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ """ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """RobertaForCausalLM""", """RobertaForMaskedLM""", """RobertaForMultipleChoice""", """RobertaForQuestionAnswering""", """RobertaForSequenceClassification""", """RobertaForTokenClassification""", """RobertaModel""", """RobertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ """TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRobertaForCausalLM""", """TFRobertaForMaskedLM""", """TFRobertaForMultipleChoice""", """TFRobertaForQuestionAnswering""", """TFRobertaForSequenceClassification""", """TFRobertaForTokenClassification""", """TFRobertaMainLayer""", """TFRobertaModel""", """TFRobertaPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ """FlaxRobertaForCausalLM""", """FlaxRobertaForMaskedLM""", """FlaxRobertaForMultipleChoice""", """FlaxRobertaForQuestionAnswering""", """FlaxRobertaForSequenceClassification""", """FlaxRobertaForTokenClassification""", """FlaxRobertaModel""", """FlaxRobertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
2
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
0
'''simple docstring''' from collections import defaultdict from math import ceil, sqrt def A_( A : int = 100_0000 , A : int = 10): UpperCamelCase = defaultdict(A) for outer_width in range(3 , (t_limit // 4) + 2): if outer_width * outer_width > t_limit: UpperCamelCase = max( ceil(sqrt(outer_width * outer_width - t_limit)) , 1) else: UpperCamelCase = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(A , 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() = }""")
3
"""simple docstring""" 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 lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = 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''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" class a : def __init__( self , _snake_case ): """simple docstring""" lowerCAmelCase = val lowerCAmelCase = None lowerCAmelCase = None def UpperCamelCase__ ( self , _snake_case ): """simple docstring""" if self.val: if val < self.val: if self.left is None: lowerCAmelCase = Node(_snake_case ) else: self.left.insert(_snake_case ) elif val > self.val: if self.right is None: lowerCAmelCase = Node(_snake_case ) else: self.right.insert(_snake_case ) else: lowerCAmelCase = val def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : List[str] , _UpperCAmelCase : str ): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase ) res.append(root.val ) inorder(root.right , _UpperCAmelCase ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int ): # Build BST if len(_UpperCAmelCase ) == 0: return arr lowerCAmelCase = Node(arr[0] ) for i in range(1 , len(_UpperCAmelCase ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCAmelCase = [] inorder(_UpperCAmelCase , _UpperCAmelCase ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
4
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
5
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
0
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class UpperCamelCase_ : def __init__( self :List[Any] , __A :Dict , __A :Tuple=14 , __A :Optional[int]=7 , __A :Any=True , __A :Tuple=True , __A :List[str]=False , __A :int=True , __A :Optional[Any]=99 , __A :Any=32 , __A :Optional[int]=4 , __A :Optional[Any]=4 , __A :Union[str, Any]=4 , __A :Tuple=37 , __A :Tuple="gelu" , __A :Union[str, Any]=0.1 , __A :List[str]=0.1 , __A :Optional[int]=512 , __A :str=0.0_2 , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = rotary_dim 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__ = initializer_range SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = vocab_size - 1 SCREAMING_SNAKE_CASE__ = vocab_size - 1 SCREAMING_SNAKE_CASE__ = vocab_size - 1 def _snake_case ( self :str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=__A , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def _snake_case ( self :int , __A :List[Any] , __A :int , __A :Optional[Any] , __A :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = 20 SCREAMING_SNAKE_CASE__ = model_class_name(__A ) SCREAMING_SNAKE_CASE__ = model.init_cache(input_ids.shape[0] , __A ) SCREAMING_SNAKE_CASE__ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) SCREAMING_SNAKE_CASE__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE__ = model( input_ids[:, :-1] , attention_mask=__A , past_key_values=__A , position_ids=__A , ) SCREAMING_SNAKE_CASE__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE__ = model( input_ids[:, -1:] , attention_mask=__A , past_key_values=outputs_cache.past_key_values , position_ids=__A , ) SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def _snake_case ( self :Any , __A :str , __A :int , __A :Any , __A :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 20 SCREAMING_SNAKE_CASE__ = model_class_name(__A ) SCREAMING_SNAKE_CASE__ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) SCREAMING_SNAKE_CASE__ = model.init_cache(input_ids.shape[0] , __A ) SCREAMING_SNAKE_CASE__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE__ = model( input_ids[:, :-1] , attention_mask=__A , past_key_values=__A , position_ids=__A , ) SCREAMING_SNAKE_CASE__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE__ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=__A , position_ids=__A , ) SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A ) SCREAMING_SNAKE_CASE__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) @require_flax class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () lowerCamelCase_ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxGPTJModelTester(self ) def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(__A , __A , __A , __A ) def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( __A , __A , __A , __A ) @tooslow def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) SCREAMING_SNAKE_CASE__ = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=__A , truncation=__A ) SCREAMING_SNAKE_CASE__ = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = model.config.eos_token_id SCREAMING_SNAKE_CASE__ = jax.jit(model.generate ) SCREAMING_SNAKE_CASE__ = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences SCREAMING_SNAKE_CASE__ = tokenizer.batch_decode(__A , skip_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(__A , __A ) @is_pt_flax_cross_test def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE__ = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE__ = getattr(__A , __A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = pt_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__A ): SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = pt_model_class(__A ).eval() SCREAMING_SNAKE_CASE__ = model_class(__A , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , __A ) SCREAMING_SNAKE_CASE__ = fx_state with torch.no_grad(): SCREAMING_SNAKE_CASE__ = pt_model(**__A ).to_tuple() SCREAMING_SNAKE_CASE__ = fx_model(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__A , __A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = model_class.from_pretrained(__A , from_pt=__A ) SCREAMING_SNAKE_CASE__ = fx_model_loaded(**__A ).to_tuple() self.assertEqual( len(__A ) , len(__A ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(__A , __A ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE__ = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE__ = getattr(__A , __A ) SCREAMING_SNAKE_CASE__ = pt_model_class(__A ).eval() SCREAMING_SNAKE_CASE__ = model_class(__A , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = load_flax_weights_in_pytorch_model(__A , fx_model.params ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = pt_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__A ): SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = pt_model(**__A ).to_tuple() SCREAMING_SNAKE_CASE__ = fx_model(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__A , __A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = pt_model_class.from_pretrained(__A , from_flax=__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = pt_model_loaded(**__A ).to_tuple() self.assertEqual( len(__A ) , len(__A ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(__A , __A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) SCREAMING_SNAKE_CASE__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(__A )
6
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() a = logging.get_logger(__name__) def _snake_case ( _snake_case : List[Any] , _snake_case : Dict=False , _snake_case : Optional[int]=False , _snake_case : str=False ) -> Optional[Any]: '''simple docstring''' _A = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''transformer.blocks.{i}.norm1.weight''', F'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm1.bias''', F'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.weight''', F'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (F'''transformer.blocks.{i}.attn.proj.bias''', F'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.weight''', F'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.norm2.bias''', F'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (F'''transformer.blocks.{i}.mlp.fc1.weight''', F'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc1.bias''', F'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.weight''', F'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''transformer.blocks.{i}.mlp.fc2.bias''', F'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _snake_case ( _snake_case : int , _snake_case : int ) -> Any: '''simple docstring''' for i in range(config.num_hidden_layers ): _A = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _A = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.weight''' ) _A = state_dict.pop(F'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _A = in_proj_weight[ : config.hidden_size, : ] _A = in_proj_bias[: config.hidden_size] _A = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _A = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _A = in_proj_weight[ -config.hidden_size :, : ] _A = in_proj_bias[-config.hidden_size :] def _snake_case ( _snake_case : Tuple ) -> str: '''simple docstring''' _A = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) def _snake_case ( _snake_case : Dict , _snake_case : str , _snake_case : Tuple ) -> str: '''simple docstring''' _A = dct.pop(_snake_case ) _A = val @torch.no_grad() def _snake_case ( _snake_case : List[str] , _snake_case : Dict ) -> List[str]: '''simple docstring''' _A = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=_snake_case ) _A = False _A = False _A = False _A = False if "vqa" in checkpoint_url: _A = True _A = 31_29 _A = 'huggingface/label-files' _A = 'vqa2-id2label.json' _A = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type='dataset' ) , 'r' ) ) _A = {int(_snake_case ): v for k, v in idalabel.items()} _A = idalabel _A = {v: k for k, v in idalabel.items()} _A = ViltForQuestionAnswering(_snake_case ) elif "nlvr" in checkpoint_url: _A = True _A = 2 _A = {0: 'False', 1: 'True'} _A = {v: k for k, v in config.idalabel.items()} _A = 3 _A = ViltForImagesAndTextClassification(_snake_case ) elif "irtr" in checkpoint_url: _A = True _A = ViltForImageAndTextRetrieval(_snake_case ) elif "mlm_itm" in checkpoint_url: _A = True _A = ViltForMaskedLM(_snake_case ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys _A = torch.hub.load_state_dict_from_url(_snake_case , map_location='cpu' )['state_dict'] _A = create_rename_keys(_snake_case , _snake_case , _snake_case , _snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) read_in_q_k_v(_snake_case , _snake_case ) if mlm_model or irtr_model: _A = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) # load state dict into HuggingFace model model.eval() if mlm_model: _A , _A = model.load_state_dict(_snake_case , strict=_snake_case ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(_snake_case ) # Define processor _A = ViltImageProcessor(size=3_84 ) _A = BertTokenizer.from_pretrained('bert-base-uncased' ) _A = ViltProcessor(_snake_case , _snake_case ) # Forward pass on example inputs (image + text) if nlvr_model: _A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=_snake_case ).raw ) _A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=_snake_case ).raw ) _A = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: _A = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=_snake_case ).raw ) if mlm_model: _A = 'a bunch of [MASK] laying on a [MASK].' else: _A = 'How many cats are there?' _A = processor(_snake_case , _snake_case , return_tensors='pt' ) _A = model(**_snake_case ) # Verify outputs if mlm_model: _A = torch.Size([1, 11, 3_05_22] ) _A = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _snake_case , atol=1E-4 ) # verify masked token prediction equals "cats" _A = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: _A = torch.Size([1, 31_29] ) _A = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , _snake_case , atol=1E-4 ) # verify vqa prediction equals "2" _A = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: _A = torch.Size([1, 2] ) _A = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) processor.save_pretrained(_snake_case ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''', 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.''' ) a = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
7
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
0
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( __snake_case : float , __snake_case : int ) -> float: __A : int = u for i in range(1 , __snake_case ): __A : Optional[int] = temp * (u - i) return temp def _lowerCAmelCase ( ) -> None: __A : Dict = int(input('enter the numbers of values: ' ) ) __A : list[list[float]] = [] for _ in range(__snake_case ): y.append([] ) for i in range(__snake_case ): for j in range(__snake_case ): y[i].append(__snake_case ) __A : int = 0 print('enter the values of parameters in a list: ' ) __A : List[str] = list(map(__snake_case , input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(__snake_case ): __A : Tuple = float(input() ) __A : Tuple = int(input('enter the value to interpolate: ' ) ) __A : Dict = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , __snake_case ): for j in range(n - i ): __A : Dict = y[j + 1][i - 1] - y[j][i - 1] __A : List[Any] = y[0][0] for i in range(1 , __snake_case ): summ += (ucal(__snake_case , __snake_case ) * y[0][i]) / math.factorial(__snake_case ) print(f'the value at {value} is {summ}' ) if __name__ == "__main__": main()
8
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _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 : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" @staticmethod @abstractmethod def _a ( _snake_case : ArgumentParser ): """simple docstring""" raise NotImplementedError() @abstractmethod def _a ( self : Union[str, Any] ): """simple docstring""" raise NotImplementedError()
9
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
0
from __future__ import annotations _lowerCAmelCase = 8.988E9 # units = N * m^s * C^-2 def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if distance < 0: raise ValueError('''Distance cannot be negative''' ) if force == 0: _UpperCamelCase = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: _UpperCamelCase = abs(__snake_case ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: _UpperCamelCase = abs(__snake_case ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: _UpperCamelCase = (COULOMBS_CONSTANT * charge_product / abs(__snake_case )) ** 0.5 return {"distance": distance} raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
10
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
'''simple docstring''' from __future__ import annotations def lowerCAmelCase (__A , __A = None , __A = None): """simple docstring""" if start is None: _a = 0 if end is None: _a = len(__A) - 1 if start >= end: return _a = (start + end) // 2 slowsort(__A , __A , __A) slowsort(__A , mid + 1 , __A) if sequence[end] < sequence[mid]: _a , _a = sequence[mid], sequence[end] slowsort(__A , __A , end - 1) if __name__ == "__main__": from doctest import testmod testmod()
11
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class _snake_case ( UpperCAmelCase_ , unittest.TestCase ): __lowerCAmelCase : Dict = FlaxAutoencoderKL @property def lowercase__ ( self): '''simple docstring''' lowercase__ : str = 4 lowercase__ : str = 3 lowercase__ : Union[str, Any] = (32, 32) lowercase__ : Optional[Any] = jax.random.PRNGKey(0) lowercase__ : int = jax.random.uniform(SCREAMING_SNAKE_CASE_ , ((batch_size, num_channels) + sizes)) return {"sample": image, "prng_key": prng_key} def lowercase__ ( self): '''simple docstring''' lowercase__ : Dict = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } lowercase__ : List[str] = self.dummy_input return init_dict, inputs_dict
12
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('socket.socket' ) @patch('builtins.open' ) def UpperCAmelCase__ ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int ) -> List[Any]: # ===== initialization ===== __lowerCamelCase : Dict = Mock() __lowerCamelCase : Union[str, Any] = conn, Mock() __lowerCamelCase : Dict = iter([1, None] ) __lowerCamelCase : Tuple = lambda UpperCAmelCase_ : next(UpperCAmelCase_ ) # ===== invoke ===== send_file(filename='mytext.txt' , testing=UpperCAmelCase_ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
13
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a__ = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self , _a , _a , _a = None , _a = None ) -> List[Any]: _a : Union[str, Any] = None _a : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) _a : Optional[int] = os.path.abspath('''examples''' ) for item in os.listdir(_a ): if item not in EXCLUDE_EXAMPLES: _a : Any = os.path.join(_a , _a ) if os.path.isfile(_a ) and ".py" in item_path: with self.subTest( tested_script=_a , feature_script=_a , tested_section='''main()''' if parser_only else '''training_function()''' , ): _a : Optional[int] = compare_against_test( os.path.join(_a , _a ) , _a , _a , _a ) _a : Union[str, Any] = '''\n'''.join(_a ) if special_strings is not None: for string in special_strings: _a : Union[str, Any] = diff.replace(_a , '''''' ) self.assertEqual(_a , '''''' ) def __lowercase ( self ) -> Optional[Any]: self.one_complete_example('''complete_nlp_example.py''' , _a ) self.one_complete_example('''complete_nlp_example.py''' , _a ) def __lowercase ( self ) -> Union[str, Any]: _a : Optional[int] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) _a : int = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _a , _a , _a ) self.one_complete_example('''complete_cv_example.py''' , _a , _a , _a ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Any = False @classmethod def __lowercase ( cls ) -> List[Any]: super().setUpClass() _a : str = tempfile.mkdtemp() _a : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) _a : int = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowercase ( cls ) -> Optional[int]: super().tearDownClass() shutil.rmtree(cls._tmpdir ) def __lowercase ( self ) -> Dict: _a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def __lowercase ( self ) -> List[str]: _a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() _a : List[str] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def __lowercase ( self ) -> Any: _a : Dict = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} """.split() _a : str = run_command(self._launch_args + testargs , return_stdout=_a ) self.assertNotIn('''epoch 0:''' , _a ) self.assertIn('''epoch 1:''' , _a ) def __lowercase ( self ) -> Dict: _a : Optional[Any] = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} """.split() _a : Optional[int] = run_command(self._launch_args + testargs , return_stdout=_a ) if torch.cuda.is_available(): _a : List[Any] = torch.cuda.device_count() else: _a : Tuple = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _a ) self.assertIn('''epoch 1:''' , _a ) else: self.assertIn('''epoch 0:''' , _a ) self.assertIn('''epoch 1:''' , _a ) @slow def __lowercase ( self ) -> Union[str, Any]: _a : List[str] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): _a : Tuple = run_command(self._launch_args + testargs , return_stdout=_a ) _a : int = re.findall('''({.+})''' , _a ) _a : int = [r for r in results if '''accuracy''' in r][-1] _a : Optional[Any] = ast.literal_eval(_a ) self.assertGreaterEqual(results['''accuracy'''] , 0.75 ) def __lowercase ( self ) -> str: _a : Optional[int] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowercase ( self ) -> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdir: _a : str = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_a , '''tracking''' ) ) ) def __lowercase ( self ) -> Optional[int]: _a : List[str] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def __lowercase ( self ) -> List[Any]: _a : Union[str, Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
14
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
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[int] = logging.get_logger(__name__) def UpperCamelCase ( __magic_name__ : np.ndarray , __magic_name__ : Union[int, Iterable[int]] , __magic_name__ : bool , __magic_name__ : int ) -> Tuple[int, int]: """simple docstring""" def constraint_to_multiple_of(__magic_name__ : Any , __magic_name__ : Any , __magic_name__ : Dict=0 , __magic_name__ : Dict=None ): lowercase__ = round(val / multiple ) * multiple if max_val is not None and x > max_val: lowercase__ = math.floor(val / multiple ) * multiple if x < min_val: lowercase__ = math.ceil(val / multiple ) * multiple return x lowercase__ = (output_size, output_size) if isinstance(__magic_name__ , __magic_name__ ) else output_size lowercase__ , lowercase__ = get_image_size(__magic_name__ ) lowercase__ , lowercase__ = output_size # determine new height and width lowercase__ = output_height / input_height lowercase__ = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width lowercase__ = scale_width else: # fit height lowercase__ = scale_height lowercase__ = constraint_to_multiple_of(scale_height * input_height , multiple=__magic_name__ ) lowercase__ = constraint_to_multiple_of(scale_width * input_width , multiple=__magic_name__ ) return (new_height, new_width) class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = ['''pixel_values'''] def __init__(self : Any , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : bool = False , _UpperCAmelCase : int = 1 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 255 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , **_UpperCAmelCase : Tuple , ) -> None: """simple docstring""" super().__init__(**_UpperCAmelCase ) lowercase__ = size if size is not None else {"""height""": 384, """width""": 384} lowercase__ = get_size_dict(_UpperCAmelCase ) lowercase__ = do_resize lowercase__ = size lowercase__ = keep_aspect_ratio lowercase__ = ensure_multiple_of lowercase__ = resample lowercase__ = do_rescale lowercase__ = rescale_factor lowercase__ = do_normalize lowercase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowercase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCamelCase__ (self : Optional[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : bool = False , _UpperCAmelCase : int = 1 , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Any , ) -> np.ndarray: """simple docstring""" lowercase__ = get_size_dict(_UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) lowercase__ = get_resize_output_image_size( _UpperCAmelCase , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=_UpperCAmelCase , multiple=_UpperCAmelCase , ) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowerCamelCase__ (self : str , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : str , ) -> int: """simple docstring""" return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowerCamelCase__ (self : str , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : int , ) -> np.ndarray: """simple docstring""" return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowerCamelCase__ (self : Any , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : int = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : int = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : Optional[Any] , ) -> PIL.Image.Image: """simple docstring""" lowercase__ = do_resize if do_resize is not None else self.do_resize lowercase__ = size if size is not None else self.size lowercase__ = get_size_dict(_UpperCAmelCase ) lowercase__ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio lowercase__ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of lowercase__ = resample if resample is not None else self.resample lowercase__ = do_rescale if do_rescale is not None else self.do_rescale lowercase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase__ = do_normalize if do_normalize is not None else self.do_normalize lowercase__ = image_mean if image_mean is not None else self.image_mean lowercase__ = image_std if image_std is not None else self.image_std lowercase__ = make_list_of_images(_UpperCAmelCase ) if not valid_images(_UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None 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. lowercase__ = [to_numpy_array(_UpperCAmelCase ) for image in images] if do_resize: lowercase__ = [self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase ) for image in images] if do_rescale: lowercase__ = [self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase ) for image in images] if do_normalize: lowercase__ = [self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase ) for image in images] lowercase__ = [to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase ) for image in images] lowercase__ = {"""pixel_values""": images} return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase ) def lowerCamelCase__ (self : Optional[int] , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[Tuple] = None ) -> Dict: """simple docstring""" lowercase__ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(_UpperCAmelCase ): lowercase__ = target_sizes.numpy() lowercase__ = [] for idx in range(len(_UpperCAmelCase ) ): lowercase__ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=_UpperCAmelCase ) lowercase__ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_UpperCAmelCase ) else: lowercase__ = logits.argmax(dim=1 ) lowercase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
15
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __A : Tuple = ( '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) ) __A : 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'), ) __A : List[Any] = ( ('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), ) __A : int = ( ('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), ) __A : Any = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 1_4]), ('2H 5D 3C AS 5S', False, [1_4, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) __A : 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), ) __A : str = ( ('JH AH TH KH QH', 2_3), ('JH 9H TH KH QH', 2_2), ('JC KH JS JD JH', 2_1), ('KH KC 3S 3H 3D', 2_0), ('8C 9C 5C 3C TC', 1_9), ('JS QS 9H TS KH', 1_8), ('7C 7S KH 2H 7H', 1_7), ('3C KH 5D 5S KH', 1_6), ('QH 8H KD JH 8S', 1_5), ('2D 6D 9D TH 7D', 1_4), ) def __a ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = randrange(len(A__ ) ), randrange(len(A__ ) ) SCREAMING_SNAKE_CASE = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __a ( A__ : int = 100 ): return (generate_random_hand() for _ in range(A__ )) @pytest.mark.parametrize("hand, expected" , A__ ) def __a ( A__ : str , A__ : List[Any] ): assert PokerHand(A__ )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , A__ ) def __a ( A__ : Optional[Any] , A__ : int ): assert PokerHand(A__ )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , A__ ) def __a ( A__ : Any , A__ : List[str] , A__ : Any ): SCREAMING_SNAKE_CASE = PokerHand(A__ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , A__ ) def __a ( A__ : Optional[int] , A__ : str ): assert PokerHand(A__ )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , A__ ) def __a ( A__ : str , A__ : Optional[int] ): assert PokerHand(A__ )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , A__ ) def __a ( A__ : Union[str, Any] , A__ : str , A__ : Optional[Any] ): assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def __a ( A__ : List[Any] , A__ : Optional[Any] , A__ : List[Any] ): assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected def __a ( ): SCREAMING_SNAKE_CASE = [PokerHand(A__ ) for hand in SORTED_HANDS] SCREAMING_SNAKE_CASE = poker_hands.copy() shuffle(A__ ) SCREAMING_SNAKE_CASE = chain(sorted(A__ ) ) for index, hand in enumerate(A__ ): assert hand == poker_hands[index] def __a ( ): # Test that five high straights are compared correctly. SCREAMING_SNAKE_CASE = [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 __a ( ): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. SCREAMING_SNAKE_CASE = PokerHand("2C 4S AS 3D 5C" ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __a ( ): # Problem number 54 from Project Euler # Testing from poker_hands.txt file SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = os.path.abspath(os.path.dirname(A__ ) ) SCREAMING_SNAKE_CASE = os.path.join(A__ , "poker_hands.txt" ) with open(A__ ) as file_hand: for line in file_hand: SCREAMING_SNAKE_CASE = line[:14].strip() SCREAMING_SNAKE_CASE = line[15:].strip() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = PokerHand(A__ ), PokerHand(A__ ) SCREAMING_SNAKE_CASE = player.compare_with(A__ ) if output == "Win": answer += 1 assert answer == 376
16
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
def __SCREAMING_SNAKE_CASE ( a__ : int ,a__ : int ,a__ : int ) -> int: if exponent == 1: return base if exponent % 2 == 0: __A : int = _modexpt(a__ ,exponent // 2 ,a__ ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(a__ ,exponent - 1 ,a__ )) % modulo_value def __SCREAMING_SNAKE_CASE ( a__ : int = 1777 ,a__ : int = 1855 ,a__ : int = 8 ) -> int: __A : Dict = base for _ in range(1 ,a__ ): __A : Optional[Any] = _modexpt(a__ ,a__ ,10**digits ) return result if __name__ == "__main__": print(f"""{solution() = }""")
17
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
'''simple docstring''' _SCREAMING_SNAKE_CASE = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _SCREAMING_SNAKE_CASE = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def __a(SCREAMING_SNAKE_CASE_ : dict[int, list[int]] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[bool] ): '''simple docstring''' _lowerCAmelCase = True _lowerCAmelCase = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) order.append(SCREAMING_SNAKE_CASE_ ) return order def __a(SCREAMING_SNAKE_CASE_ : dict[int, list[int]] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[bool] ): '''simple docstring''' _lowerCAmelCase = True _lowerCAmelCase = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return component def __a(SCREAMING_SNAKE_CASE_ : dict[int, list[int]] ): '''simple docstring''' _lowerCAmelCase = len(SCREAMING_SNAKE_CASE_ ) * [False] _lowerCAmelCase = {vert: [] for vert in range(len(SCREAMING_SNAKE_CASE_ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE_ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [] _lowerCAmelCase = len(SCREAMING_SNAKE_CASE_ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): _lowerCAmelCase = order[len(SCREAMING_SNAKE_CASE_ ) - i - 1] if not visited[vert]: _lowerCAmelCase = find_components(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) components_list.append(SCREAMING_SNAKE_CASE_ ) return components_list
18
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" import argparse import os import re import packaging.version _a = """examples/""" _a = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } _a = { """init""": """src/diffusers/__init__.py""", """setup""": """setup.py""", } _a = """README.md""" def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]: """simple docstring""" with open(__snake_case, '''r''', encoding='''utf-8''', newline='''\n''' ) as f: _UpperCamelCase = f.read() _UpperCamelCase , _UpperCamelCase = REPLACE_PATTERNS[pattern] _UpperCamelCase = replace.replace('''VERSION''', __snake_case ) _UpperCamelCase = re_pattern.sub(__snake_case, __snake_case ) with open(__snake_case, '''w''', encoding='''utf-8''', newline='''\n''' ) as f: f.write(__snake_case ) def lowerCamelCase__ ( __snake_case ) -> str: """simple docstring""" for folder, directories, fnames in os.walk(__snake_case ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__snake_case, __snake_case ), __snake_case, pattern='''examples''' ) def lowerCamelCase__ ( __snake_case, __snake_case=False ) -> Dict: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__snake_case, __snake_case, __snake_case ) if not patch: update_version_in_examples(__snake_case ) def lowerCamelCase__ ( ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = '''🤗 Transformers currently provides the following architectures''' _UpperCamelCase = '''1. Want to contribute a new model?''' with open(__snake_case, '''r''', encoding='''utf-8''', newline='''\n''' ) as f: _UpperCamelCase = f.readlines() # Find the start of the list. _UpperCamelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _UpperCamelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): _UpperCamelCase = lines[index].replace( '''https://huggingface.co/docs/diffusers/main/model_doc''', '''https://huggingface.co/docs/diffusers/model_doc''', ) index += 1 with open(__snake_case, '''w''', encoding='''utf-8''', newline='''\n''' ) as f: f.writelines(__snake_case ) def lowerCamelCase__ ( ) -> str: """simple docstring""" with open(REPLACE_FILES['''init'''], '''r''' ) as f: _UpperCamelCase = f.read() _UpperCamelCase = REPLACE_PATTERNS['''init'''][0].search(__snake_case ).groups()[0] return packaging.version.parse(__snake_case ) def lowerCamelCase__ ( __snake_case=False ) -> Optional[Any]: """simple docstring""" _UpperCamelCase = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: _UpperCamelCase = default_version.base_version elif patch: _UpperCamelCase = F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: _UpperCamelCase = F'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. _UpperCamelCase = input(F'''Which version are you releasing? [{default_version}]''' ) if len(__snake_case ) == 0: _UpperCamelCase = default_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case, patch=__snake_case ) def lowerCamelCase__ ( ) -> Any: """simple docstring""" _UpperCamelCase = get_version() _UpperCamelCase = F'''{current_version.major}.{current_version.minor + 1}.0.dev0''' _UpperCamelCase = current_version.base_version # Check with the user we got that right. _UpperCamelCase = input(F'''Which version are we developing now? [{dev_version}]''' ) if len(__snake_case ) == 0: _UpperCamelCase = dev_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") _a = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
19
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0