code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : Optional[Any] = abs(lowercase__ ) __a : int = 0 while n > 0: res += n % 10 n //= 10 return res def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : List[str] = abs(lowercase__ ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return sum(int(lowercase__ ) for c in str(abs(lowercase__ ) ) ) def lowerCamelCase (): from collections.abc import Callable from timeit import timeit def benchmark_a_function(_SCREAMING_SNAKE_CASE : Callable , _SCREAMING_SNAKE_CASE : int ) -> None: __a : Union[str, Any] = F"""{func.__name__}({value})""" __a : Any = timeit(F"""__main__.{call}""" , setup='import __main__' ) print(F"""{call:56} = {func(lowercase__ )} -- {timing:.4f} seconds""" ) for value in (262_144, 1_125_899_906_842_624, 1_267_650_600_228_229_401_496_703_205_376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(lowercase__ , lowercase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split(',' ) names.sort() __a : Union[str, Any] = 0 __a : Tuple = 0 for i, name in enumerate(_SCREAMING_SNAKE_CASE ): for letter in name: name_score += ord(_SCREAMING_SNAKE_CASE ) - 64 total_score += (i + 1) * name_score __a : Any = 0 return total_score if __name__ == "__main__": print(solution())
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): def count_of_possible_combinations(_SCREAMING_SNAKE_CASE : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(A__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): def count_of_possible_combinations_with_dp_array( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] __a : str = sum( count_of_possible_combinations_with_dp_array(target - item , A__ ) for item in array ) __a : Optional[Any] = answer return answer __a : Tuple = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(A__ , A__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): __a : Tuple = [0] * (target + 1) __a : Dict = 1 for i in range(1 , target + 1 ): for j in range(A__ ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() __lowercase : List[Any] = 3 __lowercase : Dict = 5 __lowercase : Union[str, Any] = [1, 2, 5] print(combination_sum_iv(n, array, target))
357
'''simple docstring''' __lowercase : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __lowercase : List[str] = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] ): __a : Any = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : Dict = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: __a : List[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __lowercase : Union[str, Any] = topological_sort('a', [], []) print(sort)
294
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : Union[str, Any] = jnp.ones((batch_size, length) ) / length return scores def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = None __a : List[Any] = 20 __a : List[Any] = self._get_uniform_logits(batch_size=2 , length=__lowerCAmelCase ) # tweak scores to not be uniform anymore __a : List[Any] = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch __a : Tuple = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax __a : Optional[Any] = jax.nn.softmax(__lowerCAmelCase , axis=-1 ) __a : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __a : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) __a : Optional[int] = jax.nn.softmax(temp_dist_warper_sharper(__lowerCAmelCase , scores.copy() , cur_len=__lowerCAmelCase ) , axis=-1 ) __a : Optional[int] = jax.nn.softmax(temp_dist_warper_smoother(__lowerCAmelCase , scores.copy() , cur_len=__lowerCAmelCase ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1E-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1E-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = None __a : Union[str, Any] = 10 __a : int = 2 # create ramp distribution __a : Optional[Any] = np.broadcast_to(np.arange(__lowerCAmelCase )[None, :] , (batch_size, vocab_size) ).copy() __a : str = ramp_logits[1:, : vocab_size // 2] + vocab_size __a : Dict = FlaxTopKLogitsWarper(3 ) __a : int = top_k_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case __a : List[Any] = 5 __a : int = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) __a : Union[str, Any] = np.broadcast_to(np.arange(__lowerCAmelCase )[None, :] , (batch_size, length) ).copy() __a : Optional[int] = top_k_warp_safety_check(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = None __a : Tuple = 10 __a : List[str] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) __a : Optional[int] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) __a : List[Any] = FlaxTopPLogitsWarper(0.8 ) __a : Union[str, Any] = np.exp(top_p_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 __a : Tuple = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # check edge cases with negative and extreme logits __a : Optional[Any] = np.broadcast_to(np.arange(__lowerCAmelCase )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme __a : Optional[Any] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept __a : Tuple = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) __a : Optional[Any] = top_p_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = 20 __a : Union[str, Any] = 4 __a : Tuple = 0 __a : str = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=__lowerCAmelCase ) # check that min length is applied at length 5 __a : Dict = ids_tensor((batch_size, 20) , vocab_size=20 ) __a : Optional[Any] = 5 __a : List[str] = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : Any = min_dist_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('inf' )] ) # check that min length is not applied anymore at length 15 __a : List[Any] = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : int = 15 __a : Optional[Any] = min_dist_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertFalse(jnp.isinf(__lowerCAmelCase ).any() ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = 20 __a : List[str] = 4 __a : Tuple = 0 __a : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowerCAmelCase ) # check that all scores are -inf except the bos_token_id score __a : List[str] = ids_tensor((batch_size, 1) , vocab_size=20 ) __a : Dict = 1 __a : Optional[int] = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : Tuple = logits_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 __a : int = 3 __a : Dict = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : List[Any] = logits_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertFalse(jnp.isinf(__lowerCAmelCase ).any() ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = 20 __a : str = 4 __a : Any = 0 __a : Tuple = 5 __a : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=__lowerCAmelCase , eos_token_id=__lowerCAmelCase ) # check that all scores are -inf except the eos_token_id when max_length is reached __a : Dict = ids_tensor((batch_size, 4) , vocab_size=20 ) __a : Dict = 4 __a : List[str] = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : List[str] = logits_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached __a : Tuple = 3 __a : Tuple = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : Dict = logits_processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) self.assertFalse(jnp.isinf(__lowerCAmelCase ).any() ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = 4 __a : List[str] = 10 __a : List[str] = 15 __a : List[str] = 2 __a : Optional[int] = 1 __a : Tuple = 15 # dummy input_ids and scores __a : List[Any] = ids_tensor((batch_size, sequence_length) , __lowerCAmelCase ) __a : List[Any] = input_ids.copy() __a : str = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : int = scores.copy() # instantiate all dist processors __a : Optional[int] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __a : List[str] = FlaxTopKLogitsWarper(3 ) __a : Optional[int] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __a : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=__lowerCAmelCase ) __a : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowerCAmelCase ) __a : str = FlaxForcedEOSTokenLogitsProcessor(max_length=__lowerCAmelCase , eos_token_id=__lowerCAmelCase ) __a : int = 10 # no processor list __a : Union[str, Any] = temp_dist_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Tuple = top_k_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Any = top_p_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Union[str, Any] = min_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Dict = bos_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Any = eos_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) # with processor list __a : Tuple = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __a : int = processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) # scores should be equal self.assertTrue(jnp.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = 4 __a : Dict = 10 __a : str = 15 __a : str = 2 __a : List[Any] = 1 __a : Union[str, Any] = 15 # dummy input_ids and scores __a : Union[str, Any] = ids_tensor((batch_size, sequence_length) , __lowerCAmelCase ) __a : List[Any] = input_ids.copy() __a : str = self._get_uniform_logits(__lowerCAmelCase , __lowerCAmelCase ) __a : Tuple = scores.copy() # instantiate all dist processors __a : Any = FlaxTemperatureLogitsWarper(temperature=0.5 ) __a : List[Any] = FlaxTopKLogitsWarper(3 ) __a : int = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __a : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=__lowerCAmelCase ) __a : int = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowerCAmelCase ) __a : Tuple = FlaxForcedEOSTokenLogitsProcessor(max_length=__lowerCAmelCase , eos_token_id=__lowerCAmelCase ) __a : Any = 10 # no processor list def run_no_processor_list(__a , __a , __a ): __a : Tuple = temp_dist_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : int = top_k_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : int = top_p_warp(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : int = min_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : str = bos_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) __a : Union[str, Any] = eos_dist_proc(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) return scores # with processor list def run_processor_list(__a , __a , __a ): __a : Union[str, Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __a : int = processor(__lowerCAmelCase , __lowerCAmelCase , cur_len=__lowerCAmelCase ) return scores __a : Union[str, Any] = jax.jit(__lowerCAmelCase ) __a : Dict = jax.jit(__lowerCAmelCase ) __a : List[Any] = jitted_run_no_processor_list(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __a : List[Any] = jitted_run_processor_list(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # scores should be equal self.assertTrue(jnp.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
358
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : bool = False ): if not isinstance(_UpperCamelCase , _UpperCamelCase ): __a : Any = F"""Expected string as input, found {type(_UpperCamelCase )}""" raise ValueError(_UpperCamelCase ) if not isinstance(_UpperCamelCase , _UpperCamelCase ): __a : List[Any] = F"""Expected boolean as use_pascal parameter, found {type(_UpperCamelCase )}""" raise ValueError(_UpperCamelCase ) __a : Any = input_str.split('_' ) __a : int = 0 if use_pascal else 1 __a : List[str] = words[start_index:] __a : Dict = [word[0].upper() + word[1:] for word in words_to_capitalize] __a : List[str] = '' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin __lowercase : Tuple = False @skip_mps class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = StableDiffusionAttendAndExcitePipeline A_ = False A_ = TEXT_TO_IMAGE_PARAMS A_ = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) A_ = TEXT_TO_IMAGE_IMAGE_PARAMS A_ = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(__lowerCAmelCase ) @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(__lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__lowerCAmelCase , ) __a : Dict = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=__lowerCAmelCase , set_alpha_to_one=__lowerCAmelCase , ) torch.manual_seed(0 ) __a : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __a : List[str] = CLIPTextModel(__lowerCAmelCase ) __a : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __a : Dict = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCAmelCase ( self , __a , __a=0 ): '''simple docstring''' if str(__lowerCAmelCase ).startswith('mps' ): __a : Union[str, Any] = torch.manual_seed(__lowerCAmelCase ) else: __a : Optional[int] = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) __a : List[Any] = { 'prompt': 'a cat and a frog', 'token_indices': [2, 5], 'generator': generator, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', 'max_iter_to_alter': 2, 'thresholds': {0: 0.7}, } return inputs def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'cpu' __a : str = self.get_dummy_components() __a : Optional[Any] = self.pipeline_class(**__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __a : List[Any] = self.get_dummy_inputs(__lowerCAmelCase ) __a : List[str] = pipe(**__lowerCAmelCase ).images __a : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3) ) __a : int = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) __a : List[str] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__lowerCAmelCase , 1E-3 ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 ) def __UpperCAmelCase ( self ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __UpperCAmelCase ( self ): '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7E-4 ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_save_load_local(expected_max_difference=5E-4 ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4E-4 ) @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(__lowerCAmelCase ) @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(__lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = torch.manual_seed(51 ) __a : List[Any] = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , safety_checker=__lowerCAmelCase , torch_dtype=torch.floataa ) pipe.to('cuda' ) __a : int = 'a painting of an elephant with glasses' __a : Optional[Any] = [5, 7] __a : List[Any] = pipe( prompt=__lowerCAmelCase , token_indices=__lowerCAmelCase , guidance_scale=7.5 , generator=__lowerCAmelCase , num_inference_steps=5 , max_iter_to_alter=5 , output_type='numpy' , ).images[0] __a : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy' ) assert np.abs((expected_image - image).max() ) < 5E-1
360
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = 'laion/clap-htsat-unfused' __a : Optional[Any] = tempfile.mkdtemp() def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.get_tokenizer() __a : List[str] = self.get_feature_extractor() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) __a : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __a : List[str] = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) __a : Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : int = self.get_tokenizer() __a : str = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : int = floats_list((3, 1000) ) __a : str = feature_extractor(__a , return_tensors='np' ) __a : int = processor(audios=__a , 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 __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.get_feature_extractor() __a : Any = self.get_tokenizer() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Union[str, Any] = 'This is a test string' __a : Union[str, Any] = processor(text=__a ) __a : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : str = self.get_tokenizer() __a : List[str] = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a : Optional[int] = processor.batch_decode(__a ) __a : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.get_feature_extractor() __a : Optional[int] = self.get_tokenizer() __a : int = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
294
0
'''simple docstring''' from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class __UpperCamelCase ( lowerCAmelCase_ ): A_ = CustomTokenizer pass
361
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : List[str] = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : List[str] = num_hidden_layers __a : str = num_attention_heads __a : Optional[int] = intermediate_size __a : Tuple = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[int] = max_position_embeddings __a : Dict = type_vocab_size __a : Any = type_sequence_label_size __a : Dict = initializer_range __a : Optional[Any] = num_labels __a : Optional[Any] = num_choices __a : Union[str, Any] = relative_attention __a : List[str] = position_biased_input __a : List[Any] = pos_att_type __a : Tuple = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Any = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[int] = None __a : int = None __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __a : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a )[0] __a : str = model(__a , token_type_ids=__a )[0] __a : Optional[int] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : int = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : List[Any] = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __a : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : str = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __a : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) A_ = True A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = DebertaVaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __a : Optional[Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : int = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __a : str = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): __a : int = 1 __a : str = 2 while i * i <= n: __a : List[str] = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def lowerCamelCase (): __a : Optional[Any] = 1 __a : Optional[int] = 1 while True: i += 1 t_num += i if count_divisors(lowercase_ ) > 500: break return t_num if __name__ == "__main__": print(solution())
362
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if is_torch_version('<' , '2.0.0' ) or not hasattr(_SCREAMING_SNAKE_CASE , '_dynamo' ): return False return isinstance(_SCREAMING_SNAKE_CASE , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : bool = True ): __a : int = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a : Any = is_compiled_module(_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[Any] = model __a : Union[str, Any] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = model.module if not keep_fpaa_wrapper: __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'forward' ) __a : str = model.__dict__.pop('_original_forward' , _SCREAMING_SNAKE_CASE ) if original_forward is not None: while hasattr(_SCREAMING_SNAKE_CASE , '__wrapped__' ): __a : Any = forward.__wrapped__ if forward == original_forward: break __a : str = forward if getattr(_SCREAMING_SNAKE_CASE , '_converted_to_transformer_engine' , _SCREAMING_SNAKE_CASE ): convert_model(_SCREAMING_SNAKE_CASE , to_transformer_engine=_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[str] = model __a : Optional[int] = compiled_model return model def lowerCamelCase (): PartialState().wait_for_everyone() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif PartialState().local_process_index == 0: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @contextmanager def lowerCamelCase (**_SCREAMING_SNAKE_CASE : Tuple ): for key, value in kwargs.items(): __a : Optional[int] = str(_SCREAMING_SNAKE_CASE ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ) and not hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , '__class__' , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ): return obj.__qualname__ if hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): return obj.__name__ return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): for key, value in source.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : int = destination.setdefault(_SCREAMING_SNAKE_CASE , {} ) merge_dicts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a : Tuple = value return destination def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = None ): if port is None: __a : List[str] = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
294
0
'''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 __lowercase : Optional[int] = logging.get_logger(__name__) def lowerCamelCase (_SCREAMING_SNAKE_CASE : bool , _SCREAMING_SNAKE_CASE : bool ): def run_func(_SCREAMING_SNAKE_CASE : Optional[Any] ): @wraps(UpperCamelCase__ ) def run_in_eager_mode(*_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : Dict ): return func(*UpperCamelCase__ , **UpperCamelCase__ ) @wraps(UpperCamelCase__ ) @tf.function(experimental_compile=UpperCamelCase__ ) def run_in_graph_mode(*_SCREAMING_SNAKE_CASE : List[Any] , **_SCREAMING_SNAKE_CASE : Tuple ): return func(*UpperCamelCase__ , **UpperCamelCase__ ) 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 (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : Tuple = random.Random() __a : Any = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(UpperCamelCase__ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = 42 A_ = 42 A_ = "TensorFlow" @property def __UpperCAmelCase ( self ): '''simple docstring''' return tf.__version__ def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Tuple = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) __a : Union[str, Any] = self._prepare_inference_func(_a , _a , _a ) return self._measure_speed(_inference ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : int = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) __a : List[Any] = self._prepare_train_func(_a , _a , _a ) return self._measure_speed(_train ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _a ) __a : Any = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) __a : Optional[Any] = self._prepare_inference_func(_a , _a , _a ) return self._measure_memory(_inference ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _a ) __a : str = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) __a : Optional[int] = self._prepare_train_func(_a , _a , _a ) return self._measure_memory(_train ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : str = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) __a : Any = ( hasattr(_a , 'architectures' ) and isinstance(config.architectures , _a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __a : str = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model __a : int = __import__('transformers' , fromlist=[model_class] ) __a : Optional[int] = getattr(_a , _a ) __a : Dict = model_cls(_a ) 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: __a : List[Any] = TF_MODEL_MAPPING[config.__class__](_a ) # encoder-decoder has vocab size saved differently __a : str = config.vocab_size if hasattr(_a , 'vocab_size' ) else config.encoder.vocab_size __a : Any = random_input_ids(_a , _a , _a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_a , decoder_input_ids=_a , training=_a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_a , training=_a ) __a : Any = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : int = 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.' ) __a : Any = ( hasattr(_a , 'architectures' ) and isinstance(config.architectures , _a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __a : int = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model __a : int = __import__('transformers' , fromlist=[model_class] ) __a : Union[str, Any] = getattr(_a , _a ) __a : List[str] = model_cls(_a ) 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: __a : Optional[int] = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_a ) # encoder-decoder has vocab size saved differently __a : Any = config.vocab_size if hasattr(_a , 'vocab_size' ) else config.encoder.vocab_size __a : Optional[Any] = random_input_ids(_a , _a , _a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): __a : Tuple = model(_a , decoder_input_ids=_a , labels=_a , training=_a )[0] __a : List[str] = tf.gradients(_a , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): __a : Optional[Any] = model(_a , labels=_a , training=_a )[0] __a : int = tf.gradients(_a , model.trainable_variables ) return gradients __a : Any = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def __UpperCAmelCase ( self , __a ): '''simple docstring''' 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(_a , 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 __a : Union[str, Any] = timeit.repeat( _a , repeat=self.args.repeat , number=10 , ) return min(_a ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f"""Doesn't fit on GPU. {e}""" ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' 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.' ) __a : Dict = 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.' ) __a : List[str] = '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() __a : List[str] = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) __a : Any = nvml.nvmlDeviceGetMemoryInfo(_a ) __a : Dict = meminfo.used __a : Optional[Any] = Memory(_a ) # 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.' ) __a : Optional[int] = None else: __a : int = measure_peak_memory_cpu(_a ) __a : Dict = Memory(_a ) if isinstance(_a , _a ) else memory_bytes if self.args.trace_memory_line_by_line: __a : Tuple = stop_memory_tracing(_a ) if memory is None: __a : Tuple = summary.total else: __a : List[Any] = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f"""Doesn't fit on GPU. {e}""" ) return "N/A", None
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] ): def update_area_of_max_square(_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 __a : str = update_area_of_max_square(_a , col + 1 ) __a : Tuple = update_area_of_max_square(row + 1 , col + 1 ) __a : Any = update_area_of_max_square(row + 1 , _a ) if mat[row][col]: __a : Any = 1 + min([right, diagonal, down] ) __a : Optional[Any] = max(largest_square_area[0] , _a ) return sub_problem_sol else: return 0 __a : List[Any] = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] ): def update_area_of_max_square_using_dp_array( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] __a : Any = update_area_of_max_square_using_dp_array(_a , col + 1 , _a ) __a : Union[str, Any] = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , _a ) __a : Optional[int] = update_area_of_max_square_using_dp_array(row + 1 , _a , _a ) if mat[row][col]: __a : int = 1 + min([right, diagonal, down] ) __a : Tuple = max(largest_square_area[0] , _a ) __a : List[str] = sub_problem_sol return sub_problem_sol else: return 0 __a : Dict = [0] __a : int = [[-1] * cols for _ in range(_a )] update_area_of_max_square_using_dp_array(0 , 0 , _a ) return largest_square_area[0] def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] ): __a : List[str] = [[0] * (cols + 1) for _ in range(rows + 1 )] __a : List[Any] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __a : List[str] = dp_array[row][col + 1] __a : Union[str, Any] = dp_array[row + 1][col + 1] __a : Optional[int] = dp_array[row + 1][col] if mat[row][col] == 1: __a : Dict = 1 + min(_a , _a , _a ) __a : Tuple = max(dp_array[row][col] , _a ) else: __a : Tuple = 0 return largest_square_area def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] ): __a : Tuple = [0] * (cols + 1) __a : Union[str, Any] = [0] * (cols + 1) __a : Tuple = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __a : int = current_row[col + 1] __a : Dict = next_row[col + 1] __a : Optional[Any] = next_row[col] if mat[row][col] == 1: __a : str = 1 + min(_a , _a , _a ) __a : str = max(current_row[col] , _a ) else: __a : Optional[int] = 0 __a : str = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
364
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class __UpperCamelCase : A_ = 42 A_ = None A_ = None def lowerCamelCase (_SCREAMING_SNAKE_CASE : TreeNode | None ): # Validation def is_valid_tree(_SCREAMING_SNAKE_CASE : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_SCREAMING_SNAKE_CASE ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( _SCREAMING_SNAKE_CASE : TreeNode | None , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _SCREAMING_SNAKE_CASE , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _SCREAMING_SNAKE_CASE ) ) return is_binary_search_tree_recursive_check(_SCREAMING_SNAKE_CASE , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __lowercase : List[Any] = 0 __lowercase : Union[str, Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __lowercase : Dict = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __lowercase : List[str] = tuple[int, int] class __UpperCamelCase : def __init__( self , __a , __a , __a , __a , __a , __a , ): '''simple docstring''' __a : Union[str, Any] = pos_x __a : int = pos_y __a : Any = (pos_y, pos_x) __a : Tuple = goal_x __a : Optional[int] = goal_y __a : Dict = g_cost __a : str = parent __a : Dict = self.calculate_heuristic() __a : Optional[int] = self.g_cost + self.h_cost def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.pos_x - self.goal_x __a : int = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(UpperCAmelCase_ ) + abs(UpperCAmelCase_ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self , __a ): '''simple docstring''' return self.f_cost < other.f_cost class __UpperCamelCase : def __init__( self , __a , __a ): '''simple docstring''' __a : List[str] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCAmelCase_ ) __a : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9999 , UpperCAmelCase_ ) __a : str = [self.start] __a : list[Node] = [] __a : List[str] = False def __UpperCAmelCase ( self ): '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __a : List[Any] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(UpperCAmelCase_ ) self.closed_nodes.append(UpperCAmelCase_ ) __a : List[Any] = self.get_successors(UpperCAmelCase_ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(UpperCAmelCase_ ) else: # retrieve the best current path __a : List[str] = self.open_nodes.pop(self.open_nodes.index(UpperCAmelCase_ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(UpperCAmelCase_ ) else: self.open_nodes.append(UpperCAmelCase_ ) return [self.start.pos] def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = [] for action in delta: __a : Any = parent.pos_x + action[1] __a : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase_ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( UpperCAmelCase_ , UpperCAmelCase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCAmelCase_ , ) ) return successors def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : List[str] = node __a : Dict = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __a : int = current_node.parent path.reverse() return path class __UpperCamelCase : def __init__( self , __a , __a ): '''simple docstring''' __a : Dict = AStar(UpperCAmelCase_ , UpperCAmelCase_ ) __a : str = AStar(UpperCAmelCase_ , UpperCAmelCase_ ) __a : int = False def __UpperCAmelCase ( self ): '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() __a : List[str] = self.fwd_astar.open_nodes.pop(0 ) __a : str = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( UpperCAmelCase_ , UpperCAmelCase_ ) self.fwd_astar.closed_nodes.append(UpperCAmelCase_ ) self.bwd_astar.closed_nodes.append(UpperCAmelCase_ ) __a : Any = current_bwd_node __a : Tuple = current_fwd_node __a : List[str] = { self.fwd_astar: self.fwd_astar.get_successors(UpperCAmelCase_ ), self.bwd_astar: self.bwd_astar.get_successors(UpperCAmelCase_ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(UpperCAmelCase_ ) else: # retrieve the best current path __a : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(UpperCAmelCase_ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(UpperCAmelCase_ ) else: astar.open_nodes.append(UpperCAmelCase_ ) return [self.fwd_astar.start.pos] def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.fwd_astar.retrace_path(UpperCAmelCase_ ) __a : Tuple = self.bwd_astar.retrace_path(UpperCAmelCase_ ) bwd_path.pop() bwd_path.reverse() __a : Optional[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __lowercase : Tuple = (0, 0) __lowercase : Union[str, Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __lowercase : Tuple = time.time() __lowercase : List[Any] = AStar(init, goal) __lowercase : int = a_star.search() __lowercase : List[Any] = time.time() - start_time print(f'''AStar execution time = {end_time:f} seconds''') __lowercase : List[str] = time.time() __lowercase : Tuple = BidirectionalAStar(init, goal) __lowercase : List[str] = time.time() - bd_start_time print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
365
'''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. __lowercase : Dict = 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 (_SCREAMING_SNAKE_CASE : Optional[Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): from transformers.testing_utils import pytest_terminal_summary_main __a : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE , id=_SCREAMING_SNAKE_CASE )
294
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : str = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ 'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'GraphormerForGraphClassification', 'GraphormerModel', 'GraphormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
366
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): re.sub('<n>' , '' , _SCREAMING_SNAKE_CASE ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_SCREAMING_SNAKE_CASE ) )
294
0
'''simple docstring''' from __future__ import annotations def lowerCamelCase (_SCREAMING_SNAKE_CASE : list ): if not nums: raise ValueError('List is empty' ) return sum(UpperCamelCase__ ) / len(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
367
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowercase : Any = [0, 25, 50] __lowercase : int = [25, 50, 75] __lowercase : List[str] = fuzz.membership.trimf(X, abca) __lowercase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowercase : List[Any] = np.ones(75) __lowercase : Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowercase : str = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowercase : List[Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowercase : Optional[Any] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowercase : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowercase : Optional[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowercase : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): while second != 0: __a : List[Any] = first & second first ^= second __a : Any = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __lowercase : Any = int(input('Enter the first number: ').strip()) __lowercase : int = int(input('Enter the second number: ').strip()) print(f'''{add(first, second) = }''')
368
'''simple docstring''' import sys __lowercase : Union[str, Any] = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : List[str] = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = N ): __a : Optional[int] = -sys.maxsize - 1 __a : Optional[Any] = n[:13] __a : int = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): __a : List[Any] = substr[1:] + n[cur_index] cur_index += 1 else: __a : Dict = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) __a : Optional[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
294
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase : Dict = {"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
369
'''simple docstring''' import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = CodeGenTokenizer A_ = CodeGenTokenizerFast A_ = True A_ = {"add_prefix_space": True} A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __a : Tuple = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __a : Union[str, Any] = dict(zip(__a , range(len(__a ) ) ) ) __a : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : Dict = {'unk_token': '<unk>'} __a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__a ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = 'lower newer' __a : Tuple = 'lower newer' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __a : str = 'lower newer' __a : Tuple = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) self.assertListEqual(__a , __a ) __a : List[str] = tokens + [tokenizer.unk_token] __a : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Any = 'lower newer' # Testing tokenization __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) __a : Dict = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids without special tokens __a : int = tokenizer.encode(__a , add_special_tokens=__a , add_prefix_space=__a ) __a : Tuple = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids with special tokens __a : Tuple = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Union[str, Any] = tokenizer.encode(__a , add_prefix_space=__a ) __a : int = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # Testing the unknown token __a : Any = tokens + [rust_tokenizer.unk_token] __a : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' pass def __UpperCAmelCase ( self , __a=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : Optional[int] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) # Simple input __a : List[Any] = 'This is a simple input' __a : Tuple = ['This is a simple input 1', 'This is a simple input 2'] __a : Tuple = ('This is a simple input', 'This is a pair') __a : str = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) # Pair input self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __a : str = 'This is a simple input' __a : Any = ['This is a simple input looooooooong', 'This is a simple input'] __a : Optional[int] = ('This is a simple input', 'This is a pair') __a : Optional[Any] = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __a : int = tokenizer.pad_token_id __a : List[Any] = tokenizer(__a , padding='max_length' , max_length=30 , return_tensors='np' ) __a : Union[str, Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) __a : Optional[Any] = tokenizer(*__a , padding='max_length' , max_length=60 , return_tensors='np' ) __a : List[Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = '$$$' __a : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__a , add_bos_token=__a ) __a : Union[str, Any] = 'This is a simple input' __a : List[Any] = ['This is a simple input 1', 'This is a simple input 2'] __a : List[Any] = tokenizer.bos_token_id __a : List[str] = tokenizer(__a ) __a : Optional[Any] = tokenizer(__a ) self.assertEqual(out_s.input_ids[0] , __a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __a : Any = tokenizer.decode(out_s.input_ids ) __a : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' ) __a : Optional[int] = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' __a : Tuple = '\nif len_a > len_b: result = a\nelse: result = b' __a : Optional[int] = tokenizer.encode(__a ) __a : Union[str, Any] = ['^#', re.escape('<|endoftext|>' ), '^\'\'\'', '^"""', '\n\n\n'] __a : Tuple = tokenizer.decode(__a , truncate_before_pattern=__a ) self.assertEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' pass
294
0
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class __UpperCamelCase ( _a ): A_ = (DPMSolverSDEScheduler,) A_ = 10 def __UpperCAmelCase ( self , **__a ): '''simple docstring''' __a : List[str] = { "num_train_timesteps": 1100, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "noise_sampler_seed": 0, } config.update(**_a ) return config def __UpperCAmelCase ( self ): '''simple docstring''' for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): '''simple docstring''' for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def __UpperCAmelCase ( self ): '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_a ) def __UpperCAmelCase ( self ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : str = self.get_scheduler_config() __a : Tuple = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) __a : List[Any] = self.dummy_model() __a : str = self.dummy_sample_deter * scheduler.init_noise_sigma __a : str = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): __a : List[Any] = scheduler.scale_model_input(_a , _a ) __a : Dict = model(_a , _a ) __a : Optional[Any] = scheduler.step(_a , _a , _a ) __a : Optional[int] = output.prev_sample __a : Optional[Any] = torch.sum(torch.abs(_a ) ) __a : Optional[Any] = torch.mean(torch.abs(_a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.scheduler_classes[0] __a : Dict = self.get_scheduler_config(prediction_type='v_prediction' ) __a : Any = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) __a : Union[str, Any] = self.dummy_model() __a : List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma __a : Dict = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): __a : Dict = scheduler.scale_model_input(_a , _a ) __a : str = model(_a , _a ) __a : int = scheduler.step(_a , _a , _a ) __a : List[Any] = output.prev_sample __a : Optional[Any] = torch.sum(torch.abs(_a ) ) __a : List[Any] = torch.mean(torch.abs(_a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Dict = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) __a : Any = self.dummy_model() __a : List[str] = self.dummy_sample_deter.to(_a ) * scheduler.init_noise_sigma for t in scheduler.timesteps: __a : Optional[Any] = scheduler.scale_model_input(_a , _a ) __a : List[str] = model(_a , _a ) __a : str = scheduler.step(_a , _a , _a ) __a : Optional[Any] = output.prev_sample __a : List[str] = torch.sum(torch.abs(_a ) ) __a : Dict = torch.mean(torch.abs(_a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config() __a : List[Any] = scheduler_class(**_a , use_karras_sigmas=_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) __a : List[str] = self.dummy_model() __a : List[str] = self.dummy_sample_deter.to(_a ) * scheduler.init_noise_sigma __a : Optional[int] = sample.to(_a ) for t in scheduler.timesteps: __a : Tuple = scheduler.scale_model_input(_a , _a ) __a : Any = model(_a , _a ) __a : int = scheduler.step(_a , _a , _a ) __a : int = output.prev_sample __a : List[Any] = torch.sum(torch.abs(_a ) ) __a : List[str] = torch.mean(torch.abs(_a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
370
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError('iterations must be defined as integers' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) __a : Dict = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_SCREAMING_SNAKE_CASE ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class __UpperCamelCase : def __init__( self ): '''simple docstring''' __a : List[str] = {} def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' if self.graph.get(snake_case_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: __a : Tuple = [[w, v]] if not self.graph.get(snake_case_ ): __a : Optional[Any] = [] def __UpperCAmelCase ( self ): '''simple docstring''' return list(self.graph ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if self.graph.get(snake_case_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(snake_case_ ) def __UpperCAmelCase ( self , __a=-2 , __a=-1 ): '''simple docstring''' if s == d: return [] __a : Optional[Any] = [] __a : List[Any] = [] if s == -2: __a : Union[str, Any] = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : Optional[int] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : str = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(snake_case_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) __a : Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(snake_case_ ) != 0: __a : Tuple = stack[len(snake_case_ ) - 1] else: __a : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return visited def __UpperCAmelCase ( self , __a=-1 ): '''simple docstring''' if c == -1: __a : Union[str, Any] = floor(random() * 1_0000 ) + 10 for i in range(snake_case_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): __a : str = floor(random() * c ) + 1 if n != i: self.add_pair(snake_case_ , snake_case_ , 1 ) def __UpperCAmelCase ( self , __a=-2 ): '''simple docstring''' __a : Tuple = deque() __a : str = [] if s == -2: __a : str = list(self.graph )[0] d.append(snake_case_ ) visited.append(snake_case_ ) while d: __a : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Optional[int] = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def __UpperCAmelCase ( self , __a ): '''simple docstring''' return len(self.graph[u] ) def __UpperCAmelCase ( self , __a=-2 ): '''simple docstring''' __a : str = [] __a : Any = [] if s == -2: __a : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : Dict = s __a : List[Any] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __a : List[str] = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(snake_case_ ) != 0: __a : Optional[int] = stack[len(snake_case_ ) - 1] else: __a : Union[str, Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return sorted_nodes def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = [] __a : Union[str, Any] = [] __a : Optional[int] = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : List[Any] = -2 __a : Union[str, Any] = [] __a : Optional[Any] = s __a : Optional[Any] = False __a : Any = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : Tuple = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __a : str = len(snake_case_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __a : Dict = node[1] break # check if all the children are visited if s == ss: stack.pop() __a : List[str] = True if len(snake_case_ ) != 0: __a : Any = stack[len(snake_case_ ) - 1] else: __a : Optional[Any] = False indirect_parents.append(snake_case_ ) __a : Union[str, Any] = s __a : str = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return list(snake_case_ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = [] __a : str = [] __a : Tuple = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : Optional[int] = -2 __a : List[str] = [] __a : Optional[int] = s __a : str = False __a : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __a : Optional[Any] = len(snake_case_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __a : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() __a : List[str] = True if len(snake_case_ ) != 0: __a : List[str] = stack[len(snake_case_ ) - 1] else: __a : int = False indirect_parents.append(snake_case_ ) __a : Any = s __a : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return False def __UpperCAmelCase ( self , __a=-2 , __a=-1 ): '''simple docstring''' __a : List[Any] = time() self.dfs(snake_case_ , snake_case_ ) __a : Optional[Any] = time() return end - begin def __UpperCAmelCase ( self , __a=-2 ): '''simple docstring''' __a : Any = time() self.bfs(snake_case_ ) __a : List[str] = time() return end - begin class __UpperCamelCase : def __init__( self ): '''simple docstring''' __a : List[str] = {} def __UpperCAmelCase ( self , __a , __a , __a=1 ): '''simple docstring''' if self.graph.get(snake_case_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist __a : Dict = [[w, v]] # add the other way if self.graph.get(snake_case_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist __a : Any = [[w, u]] def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if self.graph.get(snake_case_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(snake_case_ ) # the other way round if self.graph.get(snake_case_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(snake_case_ ) def __UpperCAmelCase ( self , __a=-2 , __a=-1 ): '''simple docstring''' if s == d: return [] __a : Dict = [] __a : Optional[int] = [] if s == -2: __a : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : Optional[int] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : Optional[int] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(snake_case_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) __a : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(snake_case_ ) != 0: __a : str = stack[len(snake_case_ ) - 1] else: __a : Union[str, Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return visited def __UpperCAmelCase ( self , __a=-1 ): '''simple docstring''' if c == -1: __a : Union[str, Any] = floor(random() * 1_0000 ) + 10 for i in range(snake_case_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): __a : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(snake_case_ , snake_case_ , 1 ) def __UpperCAmelCase ( self , __a=-2 ): '''simple docstring''' __a : Union[str, Any] = deque() __a : Optional[int] = [] if s == -2: __a : Tuple = list(self.graph )[0] d.append(snake_case_ ) visited.append(snake_case_ ) while d: __a : str = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __UpperCAmelCase ( self , __a ): '''simple docstring''' return len(self.graph[u] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = [] __a : List[str] = [] __a : str = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : Tuple = -2 __a : Optional[int] = [] __a : str = s __a : int = False __a : Dict = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __a : Tuple = len(snake_case_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __a : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() __a : Optional[Any] = True if len(snake_case_ ) != 0: __a : Dict = stack[len(snake_case_ ) - 1] else: __a : int = False indirect_parents.append(snake_case_ ) __a : int = s __a : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return list(snake_case_ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = [] __a : Tuple = [] __a : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) __a : List[Any] = -2 __a : Dict = [] __a : str = s __a : Optional[Any] = False __a : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __a : Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __a : Optional[int] = len(snake_case_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __a : int = node[1] break # check if all the children are visited if s == ss: stack.pop() __a : Any = True if len(snake_case_ ) != 0: __a : Any = stack[len(snake_case_ ) - 1] else: __a : Tuple = False indirect_parents.append(snake_case_ ) __a : Optional[int] = s __a : List[Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return False def __UpperCAmelCase ( self ): '''simple docstring''' return list(self.graph ) def __UpperCAmelCase ( self , __a=-2 , __a=-1 ): '''simple docstring''' __a : int = time() self.dfs(snake_case_ , snake_case_ ) __a : List[str] = time() return end - begin def __UpperCAmelCase ( self , __a=-2 ): '''simple docstring''' __a : Optional[int] = time() self.bfs(snake_case_ ) __a : str = time() return end - begin
371
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , ): '''simple docstring''' __a : List[Any] = size if size is not None else {'height': 18, 'width': 18} __a : int = parent __a : Dict = batch_size __a : Optional[int] = num_channels __a : List[Any] = image_size __a : Tuple = min_resolution __a : str = max_resolution __a : str = do_resize __a : Optional[Any] = size __a : str = apply_ocr def __UpperCAmelCase ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LayoutLMvaImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'apply_ocr' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __a : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched __a : Any = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : Tuple = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __a : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : List[str] = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __a : str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) __a : Tuple = Image.open(ds[0]['file'] ).convert('RGB' ) __a : Optional[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a : Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 __a : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False __a : List[Any] = LayoutLMvaImageProcessor(apply_ocr=__a ) __a : List[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('Input series is not valid, valid series - [2, 4, 6]' ) if len(__lowerCAmelCase ) == 0: raise ValueError('Input list must be a non empty list' ) if len(__lowerCAmelCase ) == 1: return True __a : Any = series[1] - series[0] for index in range(len(__lowerCAmelCase ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('Input series is not valid, valid series - [2, 4, 6]' ) if len(__lowerCAmelCase ) == 0: raise ValueError('Input list must be a non empty list' ) __a : Any = 0 for val in series: answer += val return answer / len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
350
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Optional[int] = botoa.client('iam' ) __a : Optional[Any] = { 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCAmelCase , AssumeRolePolicyDocument=json.dumps(_UpperCAmelCase , indent=2 ) ) __a : Optional[Any] = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCAmelCase , PolicyName=F"""{role_name}_policy_permission""" , PolicyDocument=json.dumps(_UpperCAmelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F"""role {role_name} already exists. Using existing one""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : int = botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCAmelCase )["Role"]["Arn"] def lowerCamelCase (): __a : Optional[Any] = _ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCAmelCase , ) __a : Optional[Any] = None if credentials_configuration == 0: __a : Dict = _ask_field('Enter your AWS Profile name: [default] ' , default='default' ) __a : Union[str, Any] = aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) __a : str = _ask_field('AWS Access Key ID: ' ) __a : Optional[int] = aws_access_key_id __a : List[str] = _ask_field('AWS Secret Access Key: ' ) __a : str = aws_secret_access_key __a : Tuple = _ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) __a : Any = aws_region __a : Optional[Any] = _ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCAmelCase , ) if role_management == 0: __a : int = _ask_field('Enter your IAM role name: ' ) else: __a : List[Any] = 'accelerate_sagemaker_execution_role' print(F"""Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials""" ) _create_iam_role_for_sagemaker(_UpperCAmelCase ) __a : Optional[Any] = _ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) __a : Dict = None if is_custom_docker_image: __a : Tuple = _ask_field('Enter your Docker image: ' , lambda _SCREAMING_SNAKE_CASE : str(_UpperCAmelCase ).lower() ) __a : Optional[Any] = _ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) __a : int = None if is_sagemaker_inputs_enabled: __a : Union[str, Any] = _ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _SCREAMING_SNAKE_CASE : str(_UpperCAmelCase ).lower() , ) __a : str = _ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) __a : Any = None if is_sagemaker_metrics_enabled: __a : List[Any] = _ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _SCREAMING_SNAKE_CASE : str(_UpperCAmelCase ).lower() , ) __a : Tuple = _ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) __a : Tuple = {} __a : Optional[Any] = _ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) if use_dynamo: __a : Optional[int] = 'dynamo_' __a : List[str] = _ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __a : str = _ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) if use_custom_options: __a : Union[str, Any] = _ask_options( 'Which mode do you want to use?' , _UpperCAmelCase , lambda _SCREAMING_SNAKE_CASE : TORCH_DYNAMO_MODES[int(_UpperCAmelCase )] , default='default' , ) __a : Optional[int] = _ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) __a : List[str] = _ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCAmelCase , error_message='Please enter yes or no.' , ) __a : str = 'Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: __a : Optional[Any] = _ask_options( _UpperCAmelCase , _UpperCAmelCase , lambda _SCREAMING_SNAKE_CASE : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCAmelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __a : List[Any] = _ask_field(_UpperCAmelCase , lambda _SCREAMING_SNAKE_CASE : str(_UpperCAmelCase ).lower() , default='ml.p3.2xlarge' ) __a : Optional[Any] = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __a : str = _ask_field( 'How many machines do you want use? [1]: ' , _UpperCAmelCase , default=1 , ) __a : str = _ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCAmelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCAmelCase , use_cpu=_UpperCAmelCase , dynamo_config=_UpperCAmelCase , eca_instance_type=_UpperCAmelCase , profile=_UpperCAmelCase , region=_UpperCAmelCase , iam_role_name=_UpperCAmelCase , mixed_precision=_UpperCAmelCase , num_machines=_UpperCAmelCase , sagemaker_inputs_file=_UpperCAmelCase , sagemaker_metrics_file=_UpperCAmelCase , )
351
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a ): '''simple docstring''' super().__init__() __a : int = module __a : List[Any] = nn.Sequential( nn.Linear(module.in_features , __a , bias=__a ) , nn.Linear(__a , module.out_features , bias=__a ) , ) __a : int = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=__a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' return self.module(__a , *__a , **__a ) + self.adapter(__a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module A_ = "bigscience/bloom-1b7" # Constant values A_ = 2.109659552692574 A_ = "Hello my name is" A_ = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) A_ = 10 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = AutoTokenizer.from_pretrained(self.model_name ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Models and tokenizer __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_abit.config self.assertTrue(hasattr(__a , 'quantization_config' ) ) __a : Union[str, Any] = config.to_dict() __a : Tuple = config.to_diff_dict() __a : Tuple = config.to_json_string() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit __a : List[Any] = self.model_fpaa.get_memory_footprint() __a : List[Any] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __a : Tuple = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(__a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Union[str, Any] = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BitsAndBytesConfig() __a : Tuple = True __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ) __a : List[Any] = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = BitsAndBytesConfig() with self.assertRaises(__a ): __a : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , load_in_abit=__a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(__a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(__a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __a : List[str] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Optional[int] = self.model_fpaa.to(torch.floataa ) __a : Tuple = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __a : List[Any] = self.model_fpaa.to('cpu' ) # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.half() # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.float() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=__a , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' __a : Any = 't5-small' __a : Tuple = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __a : int = AutoTokenizer.from_pretrained(cls.model_name ) __a : Union[str, Any] = 'Translate in German: Hello, my dog is cute' def __UpperCAmelCase ( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaForConditionalGeneration __a : Optional[int] = TaForConditionalGeneration._keep_in_fpaa_modules __a : List[str] = None # test with `t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[int] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : Any = model.generate(**__a ) # test with `flan-t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[Any] = model.generate(**__a ) __a : Optional[int] = modules def __UpperCAmelCase ( self ): '''simple docstring''' import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[str] = model.generate(**__a ) # test with `flan-t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : int = model.generate(**__a ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # model_name __a : List[Any] = 'bigscience/bloom-560m' __a : Union[str, Any] = 't5-small' # Different types of model __a : Optional[Any] = AutoModel.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Sequence classification model __a : Dict = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=__a , device_map='auto' ) # CausalLM model __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Seq2seq model __a : Any = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' del self.pipe gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __a : str = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=__a , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __a : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __a : str = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'facebook/opt-350m' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __a : Tuple = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __a : Tuple = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(__a ) ): __a : str = LoRALayer(module.q_proj , rank=16 ) __a : str = LoRALayer(module.k_proj , rank=16 ) __a : Optional[int] = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __a : List[str] = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __a : int = model.forward(**__a ) out.logits.norm().backward() for module in model.modules(): if isinstance(__a , __a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(__a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "gpt2-xl" A_ = 3.3191854854152187
294
0
'''simple docstring''' class __UpperCamelCase : """simple docstring""" def __init__( self , __a ): '''simple docstring''' __a : str = val __a : Dict = None __a : str = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a : Optional[Any] = Node(__SCREAMING_SNAKE_CASE ) else: self.left.insert(__SCREAMING_SNAKE_CASE ) elif val > self.val: if self.right is None: __a : List[str] = Node(__SCREAMING_SNAKE_CASE ) else: self.right.insert(__SCREAMING_SNAKE_CASE ) else: __a : Any = val def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict ): # Recursive traversal if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): # Build BST if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a : List[str] = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a : List[str] = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
352
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAmelCase_ ): A_ = None A_ = None A_ = None A_ = None class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a=1 , __a=0 , __a=2 , __a=512 , __a="cls" , __a=False , __a=True , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Any = project_dim __a : Optional[Any] = pooler_fn __a : int = learn_encoder __a : str = use_attention_mask class __UpperCamelCase ( lowerCAmelCase_ ): A_ = [r"pooler", r"logit_scale"] A_ = [r"position_ids", r"predictions.decoder.bias"] A_ = "roberta" A_ = RobertaSeriesConfig def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Optional[Any] = XLMRobertaModel(__a ) __a : str = nn.Linear(config.hidden_size , config.project_dim ) __a : Optional[int] = getattr(__a , 'has_pre_transformation' , __a ) if self.has_pre_transformation: __a : int = nn.Linear(config.hidden_size , config.project_dim ) __a : List[str] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Tuple = self.base_model( input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , ) if self.has_pre_transformation: __a : Optional[Any] = outputs['hidden_states'][-2] __a : Optional[int] = self.pre_LN(__a ) __a : Union[str, Any] = self.transformation_pre(__a ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __a : Optional[Any] = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
294
0
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version __lowercase = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize __lowercase = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' __lowercase = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' __lowercase = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def __UpperCAmelCase ( self , __a , __a , __a=0.9 , __a=3 , __a=0.5 ): '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): __a : str = [ meteor_score.single_meteor_score( word_tokenize(__a ) , word_tokenize(__a ) , alpha=__a , beta=__a , gamma=__a ) for ref, pred in zip(__a , __a ) ] else: __a : Tuple = [ meteor_score.single_meteor_score(__a , __a , alpha=__a , beta=__a , gamma=__a ) for ref, pred in zip(__a , __a ) ] return {"meteor": np.mean(__a )}
353
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=10 , __a=3 , __a=2 , __a=2 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a="divided_space_time" , __a=None , ): '''simple docstring''' __a : Union[str, Any] = parent __a : Optional[Any] = batch_size __a : str = image_size __a : List[Any] = num_channels __a : Dict = patch_size __a : List[str] = num_frames __a : Optional[Any] = is_training __a : Optional[Any] = use_labels __a : Optional[int] = hidden_size __a : List[Any] = num_hidden_layers __a : Optional[Any] = num_attention_heads __a : Optional[int] = intermediate_size __a : Optional[Any] = hidden_act __a : Optional[int] = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Tuple = attention_type __a : Optional[Any] = initializer_range __a : Optional[int] = scope __a : str = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token __a : Optional[int] = (image_size // patch_size) ** 2 __a : str = (num_frames) * self.num_patches_per_frame + 1 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) __a : Union[str, Any] = None if self.use_labels: __a : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) __a : Optional[Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) __a : Dict = self.num_labels return config def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Union[str, Any] = TimesformerModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __a : Any = model(_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TimesformerForVideoClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __a : Dict = model(_lowerCAmelCase ) # verify the logits shape __a : Union[str, Any] = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , _lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() __a , __a , __a : str = config_and_inputs __a : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () A_ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = TimesformerModelTester(self ) __a : Optional[Any] = ConfigTester( self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 ) def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : Any = copy.deepcopy(_lowerCAmelCase ) if return_labels: if model_class in get_values(_lowerCAmelCase ): __a : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCAmelCase ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='TimeSformer does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Optional[Any] = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : int = model_class(_lowerCAmelCase ) __a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : List[Any] = [*signature.parameters.keys()] __a : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*_lowerCAmelCase ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Any = TimesformerModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.has_attentions: pass else: __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : str = True for model_class in self.all_model_classes: __a : List[str] = self.model_tester.seq_length __a : Union[str, Any] = self.model_tester.num_frames __a : str = True __a : int = False __a : Optional[int] = True __a : int = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): __a : Any = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) __a : List[str] = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a : str = True __a : List[str] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): __a : List[Any] = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) __a : Any = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) __a : List[str] = len(_lowerCAmelCase ) # Check attention is always last and order is fine __a : Tuple = True __a : List[str] = True __a : Optional[int] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): __a : str = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) self.assertEqual(out_len + 1 , len(_lowerCAmelCase ) ) __a : List[Any] = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : Tuple = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): __a : Union[str, Any] = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) __a : Union[str, Any] = outputs.hidden_states __a : Optional[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) __a : List[Any] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Optional[Any] = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[int] = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def lowerCamelCase (): __a : Tuple = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) __a : Union[str, Any] = np.load(_lowerCAmelCase ) return list(_lowerCAmelCase ) @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400' ).to( _lowerCAmelCase ) __a : Dict = self.default_image_processor __a : List[str] = prepare_video() __a : List[Any] = image_processor(video[:8] , return_tensors='pt' ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): __a : str = model(**_lowerCAmelCase ) # verify the logits __a : Dict = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) __a : Optional[int] = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1E-4 ) )
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __lowercase : str = logging.get_logger(__name__) # General docstring __lowercase : List[str] = 'MobileNetV1Config' # Base docstring __lowercase : Tuple = 'google/mobilenet_v1_1.0_224' __lowercase : List[Any] = [1, 10_24, 7, 7] # Image classification docstring __lowercase : int = 'google/mobilenet_v1_1.0_224' __lowercase : Any = 'tabby, tabby cat' __lowercase : Dict = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any]=None ): __a : Dict = {} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = model.mobilenet_va else: __a : List[Any] = model __a : Dict = 'MobilenetV1/Conv2d_0/' __a : Dict = backbone.conv_stem.convolution.weight __a : Optional[Any] = backbone.conv_stem.normalization.bias __a : int = backbone.conv_stem.normalization.weight __a : int = backbone.conv_stem.normalization.running_mean __a : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): __a : int = i + 1 __a : Dict = i * 2 __a : Dict = backbone.layer[pt_index] __a : Dict = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" __a : Union[str, Any] = pointer.convolution.weight __a : Optional[Any] = pointer.normalization.bias __a : Union[str, Any] = pointer.normalization.weight __a : List[Any] = pointer.normalization.running_mean __a : Tuple = pointer.normalization.running_var __a : List[str] = backbone.layer[pt_index + 1] __a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" __a : Optional[int] = pointer.convolution.weight __a : List[str] = pointer.normalization.bias __a : Dict = pointer.normalization.weight __a : Dict = pointer.normalization.running_mean __a : Optional[int] = pointer.normalization.running_var if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Any = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __a : Optional[int] = model.classifier.weight __a : List[Any] = model.classifier.bias return tf_to_pt_map def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __a : Union[str, Any] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) __a : List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = array # Build TF to PyTorch weights loading map __a : Optional[int] = _build_tf_to_pytorch_map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue __a : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __a : Optional[Any] = np.transpose(_SCREAMING_SNAKE_CASE , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __a : Union[str, Any] = array.squeeze().transpose() else: __a : Dict = np.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) __a : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) tf_weights.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp_1' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/ExponentialMovingAverage' , _SCREAMING_SNAKE_CASE ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def lowerCamelCase (_SCREAMING_SNAKE_CASE : torch.Tensor , _SCREAMING_SNAKE_CASE : nn.Convad ): __a , __a : Any = features.shape[-2:] __a , __a : int = conv_layer.stride __a , __a : Any = conv_layer.kernel_size if in_height % stride_height == 0: __a : int = max(kernel_height - stride_height , 0 ) else: __a : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __a : Any = max(kernel_width - stride_width , 0 ) else: __a : str = max(kernel_width - (in_width % stride_width) , 0 ) __a : int = pad_along_width // 2 __a : Dict = pad_along_width - pad_left __a : List[str] = pad_along_height // 2 __a : Union[str, Any] = pad_along_height - pad_top __a : str = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'constant' , 0.0 ) class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a , __a , __a , __a = 1 , __a = 1 , __a = False , __a = True , __a = True , ): '''simple docstring''' super().__init__() __a : Optional[int] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) __a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __a : Union[str, Any] = nn.Convad( in_channels=__a , out_channels=__a , kernel_size=__a , stride=__a , padding=__a , groups=__a , bias=__a , padding_mode='zeros' , ) if use_normalization: __a : List[str] = nn.BatchNormad( num_features=__a , eps=config.layer_norm_eps , momentum=0.9997 , affine=__a , track_running_stats=__a , ) else: __a : Tuple = None if use_activation: if isinstance(__a , __a ): __a : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , __a ): __a : Union[str, Any] = ACTaFN[config.hidden_act] else: __a : Dict = config.hidden_act else: __a : List[Any] = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.tf_padding: __a : Union[str, Any] = apply_tf_padding(__a , self.convolution ) __a : Union[str, Any] = self.convolution(__a ) if self.normalization is not None: __a : str = self.normalization(__a ) if self.activation is not None: __a : Optional[int] = self.activation(__a ) return features class __UpperCamelCase ( lowerCAmelCase_ ): A_ = MobileNetVaConfig A_ = load_tf_weights_in_mobilenet_va A_ = "mobilenet_v1" A_ = "pixel_values" A_ = False def __UpperCAmelCase ( self , __a ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __lowercase : Any = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowercase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a = True ): '''simple docstring''' super().__init__(__a ) __a : Optional[int] = config __a : str = 32 __a : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) __a : Union[str, Any] = MobileNetVaConvLayer( __a , in_channels=config.num_channels , out_channels=__a , kernel_size=3 , stride=2 , ) __a : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __a : Any = nn.ModuleList() for i in range(13 ): __a : Union[str, Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 __a : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=3 , stride=strides[i] , groups=__a , ) ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=1 , ) ) __a : Optional[int] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __UpperCAmelCase ( self , __a ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a : int = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __a : Union[str, Any] = self.conv_stem(__a ) __a : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __a : List[str] = layer_module(__a ) if output_hidden_states: __a : List[Any] = all_hidden_states + (hidden_states,) __a : str = hidden_states if self.pooler is not None: __a : Union[str, Any] = torch.flatten(self.pooler(__a ) , start_dim=1 ) else: __a : int = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__a , pooler_output=__a , hidden_states=__a , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Tuple = config.num_labels __a : Tuple = MobileNetVaModel(__a ) __a : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __a : Any = nn.Dropout(config.classifier_dropout_prob , inplace=__a ) __a : Any = nn.Linear(__a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Dict = self.mobilenet_va(__a , output_hidden_states=__a , return_dict=__a ) __a : List[str] = outputs.pooler_output if return_dict else outputs[1] __a : int = self.classifier(self.dropout(__a ) ) __a : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a : int = 'single_label_classification' else: __a : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __a : Optional[Any] = MSELoss() if self.num_labels == 1: __a : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __a : List[str] = CrossEntropyLoss() __a : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a : Tuple = BCEWithLogitsLoss() __a : Optional[int] = loss_fct(__a , __a ) if not return_dict: __a : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=__a , logits=__a , hidden_states=outputs.hidden_states , )
294
0
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __lowercase : Any = '▁' __lowercase : Union[str, Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): A_ = BertGenerationTokenizer A_ = False A_ = True def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() __a : List[str] = BertGenerationTokenizer(_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = '<s>' __a : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1002 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = BertGenerationTokenizer(_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE ) __a : Any = tokenizer.tokenize('This is a test' ) self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [285, 46, 10, 170, 382] , ) __a : List[str] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __a : Optional[Any] = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) self.assertListEqual( _SCREAMING_SNAKE_CASE , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __a : List[Any] = tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ) self.assertListEqual( _SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = 'Hello World!' __a : List[str] = [1_8536, 2260, 101] self.assertListEqual(_SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(_SCREAMING_SNAKE_CASE ) ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = ( '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' ) __a : Optional[Any] = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, ] self.assertListEqual(_SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(_SCREAMING_SNAKE_CASE ) ) @require_torch @slow def __UpperCAmelCase ( self ): '''simple docstring''' import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __a : int = list(self.big_tokenizer.get_vocab().keys() )[:10] __a : Union[str, Any] = ' '.join(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = self.big_tokenizer.encode_plus(_SCREAMING_SNAKE_CASE , return_tensors='pt' , return_token_type_ids=_SCREAMING_SNAKE_CASE ) __a : Tuple = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_SCREAMING_SNAKE_CASE ) __a : int = BertGenerationConfig() __a : Dict = BertGenerationEncoder(_SCREAMING_SNAKE_CASE ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_SCREAMING_SNAKE_CASE ) model(**_SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = {'input_ids': [[3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114], [448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=_SCREAMING_SNAKE_CASE , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
355
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase : str = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "dhaka" , _SCREAMING_SNAKE_CASE : int = 5 ): __a : Optional[Any] = min(_SCREAMING_SNAKE_CASE , 50 ) # Prevent abuse! __a : Optional[Any] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } __a : Tuple = requests.get('https://www.google.com/search' , params=_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ) __a : Dict = BeautifulSoup(html.text , 'html.parser' ) __a : List[str] = ''.join( re.findall(r'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) __a : Optional[Any] = json.dumps(_SCREAMING_SNAKE_CASE ) __a : List[str] = json.loads(_SCREAMING_SNAKE_CASE ) __a : List[Any] = re.findall( r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , _SCREAMING_SNAKE_CASE , ) if not matched_google_image_data: return 0 __a : Tuple = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(_SCREAMING_SNAKE_CASE ) , ) __a : Optional[Any] = re.findall( r'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , _SCREAMING_SNAKE_CASE , ) for index, fixed_full_res_image in enumerate(_SCREAMING_SNAKE_CASE ): if index >= max_images: return index __a : List[str] = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Tuple = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Dict = urllib.request.build_opener() __a : Union[str, Any] = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(_SCREAMING_SNAKE_CASE ) __a : List[Any] = F"""query_{query.replace(" " , "_" )}""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): os.makedirs(_SCREAMING_SNAKE_CASE ) urllib.request.urlretrieve( # noqa: S310 _SCREAMING_SNAKE_CASE , F"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: __lowercase : Optional[int] = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print('Please provide a search term.') raise
294
0
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class __UpperCamelCase ( snake_case_ ): A_ = "M-CLIP" def __init__( self , __a=1024 , __a=768 , **__a ): '''simple docstring''' __a : Tuple = transformerDimSize __a : Optional[Any] = imageDimSize super().__init__(**__a ) class __UpperCamelCase ( snake_case_ ): A_ = MCLIPConfig def __init__( self , __a , *__a , **__a ): '''simple docstring''' super().__init__(__a , *__a , **__a ) __a : Optional[int] = XLMRobertaModel(__a ) __a : List[str] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : List[Any] = self.transformer(input_ids=__a , attention_mask=__a )[0] __a : Optional[Any] = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(__a ), embs
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split(',' ) names.sort() __a : Union[str, Any] = 0 __a : Tuple = 0 for i, name in enumerate(_SCREAMING_SNAKE_CASE ): for letter in name: name_score += ord(_SCREAMING_SNAKE_CASE ) - 64 total_score += (i + 1) * name_score __a : Any = 0 return total_score if __name__ == "__main__": print(solution())
294
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Any = { "configuration_xlm_roberta": [ "XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaConfig", "XLMRobertaOnnxConfig", ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[int] = ["XLMRobertaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ["XLMRobertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ "XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaForCausalLM", "XLMRobertaForMaskedLM", "XLMRobertaForMultipleChoice", "XLMRobertaForQuestionAnswering", "XLMRobertaForSequenceClassification", "XLMRobertaForTokenClassification", "XLMRobertaModel", "XLMRobertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ "TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMRobertaForCausalLM", "TFXLMRobertaForMaskedLM", "TFXLMRobertaForMultipleChoice", "TFXLMRobertaForQuestionAnswering", "TFXLMRobertaForSequenceClassification", "TFXLMRobertaForTokenClassification", "TFXLMRobertaModel", "TFXLMRobertaPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Dict = [ "FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxXLMRobertaForMaskedLM", "FlaxXLMRobertaForCausalLM", "FlaxXLMRobertaForMultipleChoice", "FlaxXLMRobertaForQuestionAnswering", "FlaxXLMRobertaForSequenceClassification", "FlaxXLMRobertaForTokenClassification", "FlaxXLMRobertaModel", "FlaxXLMRobertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys __lowercase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
357
'''simple docstring''' __lowercase : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __lowercase : List[str] = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] ): __a : Any = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : Dict = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: __a : List[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __lowercase : Union[str, Any] = topological_sort('a', [], []) print(sort)
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : str = len(A__ ) for i in range(length - 1 ): __a : Dict = i for k in range(i + 1 , A__ ): if collection[k] < collection[least]: __a : Any = k if least != i: __a , __a : Optional[Any] = (collection[i], collection[least]) return collection if __name__ == "__main__": __lowercase : Any = input('Enter numbers separated by a comma:\n').strip() __lowercase : Optional[int] = [int(item) for item in user_input.split(',')] print(selection_sort(unsorted))
358
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class __UpperCamelCase ( unittest.TestCase ): @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = pipeline( task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused' ) __a : List[str] = load_dataset('ashraq/esc50' ) __a : str = dataset['train']['audio'][-1]['array'] __a : int = audio_classifier(__a , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__a ) , [{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}] , ) @unittest.skip('No models are available in TF' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = pipeline( task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , ) # This is an audio of a dog __a : Tuple = load_dataset('ashraq/esc50' ) __a : Tuple = dataset['train']['audio'][-1]['array'] __a : int = audio_classifier(__a , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__a ) , [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ] , ) __a : Optional[Any] = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(__a ) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) __a : int = audio_classifier( [audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5 ) self.assertEqual( nested_simplify(__a ) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) @unittest.skip('No models are available in TF' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
360
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = 'laion/clap-htsat-unfused' __a : Optional[Any] = tempfile.mkdtemp() def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.get_tokenizer() __a : List[str] = self.get_feature_extractor() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) __a : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __a : List[str] = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) __a : Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : int = self.get_tokenizer() __a : str = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : int = floats_list((3, 1000) ) __a : str = feature_extractor(__a , return_tensors='np' ) __a : int = processor(audios=__a , 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 __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.get_feature_extractor() __a : Any = self.get_tokenizer() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Union[str, Any] = 'This is a test string' __a : Union[str, Any] = processor(text=__a ) __a : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : str = self.get_tokenizer() __a : List[str] = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a : Optional[int] = processor.batch_decode(__a ) __a : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.get_feature_extractor() __a : Optional[int] = self.get_tokenizer() __a : int = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
294
0
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=4 , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : Dict = is_training __a : Union[str, Any] = use_attention_mask __a : Any = use_token_type_ids __a : List[Any] = use_labels __a : Optional[Any] = vocab_size __a : Dict = hidden_size __a : Tuple = num_hidden_layers __a : Tuple = num_attention_heads __a : Tuple = intermediate_size __a : Tuple = hidden_act __a : int = hidden_dropout_prob __a : Optional[int] = attention_probs_dropout_prob __a : str = max_position_embeddings __a : List[str] = type_vocab_size __a : List[Any] = type_sequence_label_size __a : Tuple = initializer_range __a : str = num_choices def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[str] = None if self.use_attention_mask: __a : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __a : Dict = None if self.use_token_type_ids: __a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Dict = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.prepare_config_and_inputs() __a , __a , __a , __a : int = config_and_inputs __a : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a , __a : Optional[int] = config_and_inputs __a : List[Any] = True __a : str = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __UpperCamelCase ( __lowercase , unittest.TestCase ): A_ = True A_ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = FlaxRobertaModelTester(self ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: __a : Union[str, Any] = model_class_name.from_pretrained('roberta-base' , from_pt=UpperCAmelCase__ ) __a : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase__ )
361
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : List[str] = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : List[str] = num_hidden_layers __a : str = num_attention_heads __a : Optional[int] = intermediate_size __a : Tuple = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[int] = max_position_embeddings __a : Dict = type_vocab_size __a : Any = type_sequence_label_size __a : Dict = initializer_range __a : Optional[Any] = num_labels __a : Optional[Any] = num_choices __a : Union[str, Any] = relative_attention __a : List[str] = position_biased_input __a : List[Any] = pos_att_type __a : Tuple = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Any = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[int] = None __a : int = None __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __a : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a )[0] __a : str = model(__a , token_type_ids=__a )[0] __a : Optional[int] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : int = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : List[Any] = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __a : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : str = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __a : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) A_ = True A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = DebertaVaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __a : Optional[Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : int = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __a : str = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
294
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowercase : Optional[Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[Any] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
362
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if is_torch_version('<' , '2.0.0' ) or not hasattr(_SCREAMING_SNAKE_CASE , '_dynamo' ): return False return isinstance(_SCREAMING_SNAKE_CASE , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : bool = True ): __a : int = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a : Any = is_compiled_module(_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[Any] = model __a : Union[str, Any] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = model.module if not keep_fpaa_wrapper: __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'forward' ) __a : str = model.__dict__.pop('_original_forward' , _SCREAMING_SNAKE_CASE ) if original_forward is not None: while hasattr(_SCREAMING_SNAKE_CASE , '__wrapped__' ): __a : Any = forward.__wrapped__ if forward == original_forward: break __a : str = forward if getattr(_SCREAMING_SNAKE_CASE , '_converted_to_transformer_engine' , _SCREAMING_SNAKE_CASE ): convert_model(_SCREAMING_SNAKE_CASE , to_transformer_engine=_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[str] = model __a : Optional[int] = compiled_model return model def lowerCamelCase (): PartialState().wait_for_everyone() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif PartialState().local_process_index == 0: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @contextmanager def lowerCamelCase (**_SCREAMING_SNAKE_CASE : Tuple ): for key, value in kwargs.items(): __a : Optional[int] = str(_SCREAMING_SNAKE_CASE ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ) and not hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , '__class__' , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ): return obj.__qualname__ if hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): return obj.__name__ return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): for key, value in source.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : int = destination.setdefault(_SCREAMING_SNAKE_CASE , {} ) merge_dicts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a : Tuple = value return destination def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = None ): if port is None: __a : List[str] = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
294
0
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( _A , unittest.TestCase ): A_ = LEDTokenizer A_ = LEDTokenizerFast A_ = True def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() __a : int = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] __a : Any = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __a : str = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : Union[str, Any] = {'unk_token': '<unk>'} __a : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__SCREAMING_SNAKE_CASE ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LEDTokenizer.from_pretrained('allenai/led-base-16384' ) @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LEDTokenizerFast.from_pretrained('allenai/led-base-16384' ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __a : Optional[Any] = [0, 250, 251, 1_7818, 13, 3_9186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Union[str, Any] = tokenizer(__SCREAMING_SNAKE_CASE , max_length=len(__SCREAMING_SNAKE_CASE ) , padding=__SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a : Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : List[str] = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIn('input_ids' , __SCREAMING_SNAKE_CASE ) self.assertIn('attention_mask' , __SCREAMING_SNAKE_CASE ) self.assertNotIn('labels' , __SCREAMING_SNAKE_CASE ) self.assertNotIn('decoder_attention_mask' , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = [ 'Summary of the text.', 'Another summary.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer(text_target=__SCREAMING_SNAKE_CASE , max_length=32 , padding='max_length' , return_tensors='pt' ) self.assertEqual(32 , targets['input_ids'].shape[1] ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer( ['I am a small frog' * 1024, 'I am a small frog'] , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = ['A long paragraph for summarization.'] __a : List[Any] = [ 'Summary of the text.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Any = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='pt' ) __a : int = tokenizer(text_target=__SCREAMING_SNAKE_CASE , return_tensors='pt' ) __a : Dict = inputs['input_ids'] __a : Any = targets['input_ids'] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def __UpperCAmelCase ( self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[Any] = ['Summary of the text.', 'Another summary.'] __a : List[str] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a : List[str] = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = [[0] * len(__SCREAMING_SNAKE_CASE ) for x in encoded_output['input_ids']] __a : Dict = tokenizer.pad(__SCREAMING_SNAKE_CASE ) self.assertSequenceEqual(outputs['global_attention_mask'] , __SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : int = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __a : Tuple = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __a : Optional[int] = 'A, <mask> AllenNLP sentence.' __a : Optional[int] = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) __a : int = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) __a : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) __a : List[str] = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
0
'''simple docstring''' from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class __UpperCamelCase ( yaml.SafeLoader ): def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Dict = [self.constructed_objects[key_node] for key_node, _ in node.value] __a : Optional[int] = [tuple(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else key for key in keys] __a : Dict = Counter(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f"""Got duplicate yaml keys: {duplicate_keys}""" ) def __UpperCAmelCase ( self , __a , __a=False ): '''simple docstring''' __a : Any = super().construct_mapping(_SCREAMING_SNAKE_CASE , deep=_SCREAMING_SNAKE_CASE ) self._check_no_duplicates_on_constructed_node(_SCREAMING_SNAKE_CASE ) return mapping def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): __a : Any = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: __a : List[str] = full_content[1:].index('---' ) + 1 __a : str = "\n".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(__snake_case ) class __UpperCamelCase ( __SCREAMING_SNAKE_CASE ): A_ = {"train_eval_index"} # train-eval-index in the YAML metadata @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as readme_file: __a : Dict = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(_SCREAMING_SNAKE_CASE ) else: return cls() def __UpperCAmelCase ( self , __a ): '''simple docstring''' if path.exists(): with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as readme_file: __a : List[Any] = readme_file.read() else: __a : Optional[int] = None __a : int = self._to_readme(_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self , __a = None ): '''simple docstring''' if readme_content is not None: __a : Optional[Any] = _split_yaml_from_readme(_SCREAMING_SNAKE_CASE ) __a : List[Any] = "---\n" + self.to_yaml_string() + "---\n" + content else: __a : str = "---\n" + self.to_yaml_string() + "---\n" return full_content @classmethod def __UpperCAmelCase ( cls , __a ): '''simple docstring''' __a : Tuple = yaml.load(_SCREAMING_SNAKE_CASE , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields __a : Union[str, Any] = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=_SCREAMING_SNAKE_CASE , allow_unicode=_SCREAMING_SNAKE_CASE , encoding='utf-8' , ).decode('utf-8' ) __lowercase : int = { 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser __lowercase : Union[str, Any] = ArgumentParser(usage='Validate the yaml metadata block of a README.md file.') ap.add_argument('readme_filepath') __lowercase : Optional[Any] = ap.parse_args() __lowercase : Any = Path(args.readme_filepath) __lowercase : int = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
364
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class __UpperCamelCase : A_ = 42 A_ = None A_ = None def lowerCamelCase (_SCREAMING_SNAKE_CASE : TreeNode | None ): # Validation def is_valid_tree(_SCREAMING_SNAKE_CASE : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_SCREAMING_SNAKE_CASE ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( _SCREAMING_SNAKE_CASE : TreeNode | None , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _SCREAMING_SNAKE_CASE , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _SCREAMING_SNAKE_CASE ) ) return is_binary_search_tree_recursive_check(_SCREAMING_SNAKE_CASE , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''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 (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[int]: __a : List[str] = 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}}' ) __a : int = DatasetInfosDict.from_directory(_a ) 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 (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : DatasetInfo ) -> Optional[int]: __a : Optional[Any] = str(_a ) dataset_info.write_to_directory(_a ) __a : Tuple = DatasetInfo.from_directory(_a ) assert dataset_info == reloaded assert os.path.exists(os.path.join(_a , 'dataset_info.json' ) ) def lowerCamelCase () -> Tuple: __a : List[Any] = 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=1_337 , post_processing_size=442 , dataset_size=1_234 , size_in_bytes=1_337 + 442 + 1_234 , ) __a : Optional[Any] = dataset_info._to_yaml_dict() assert sorted(_a ) == 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) ) __a : List[Any] = yaml.safe_dump(_a ) __a : Any = yaml.safe_load(_a ) assert dataset_info_yaml_dict == reloaded def lowerCamelCase () -> List[str]: __a : List[Any] = DatasetInfo() __a : 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=1_337 ), } ), ] , ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : DatasetInfosDict ) -> List[Any]: __a : Dict = str(_a ) dataset_infos_dict.write_to_directory(_a ) __a : Any = DatasetInfosDict.from_directory(_a ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __a : 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 __a : Optional[Any] = 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(_a , 'README.md' ) )
365
'''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. __lowercase : Dict = 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 (_SCREAMING_SNAKE_CASE : Optional[Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): from transformers.testing_utils import pytest_terminal_summary_main __a : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE , id=_SCREAMING_SNAKE_CASE )
294
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal __lowercase : Any = datasets.utils.logging.get_logger(__name__) __lowercase : int = ["""names""", """prefix"""] __lowercase : Union[str, Any] = ["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""] __lowercase : List[Any] = ["""encoding_errors""", """on_bad_lines"""] __lowercase : Dict = ["""date_format"""] @dataclass class __UpperCamelCase ( datasets.BuilderConfig ): A_ = "," A_ = None A_ = "infer" A_ = None A_ = None A_ = None A_ = None A_ = None A_ = True A_ = None A_ = None A_ = None A_ = None A_ = False A_ = None A_ = None A_ = None A_ = True A_ = True A_ = False A_ = True A_ = None A_ = "." A_ = None A_ = '"' A_ = 0 A_ = None A_ = None A_ = None A_ = None A_ = True A_ = True A_ = 0 A_ = True A_ = False A_ = None A_ = 10000 A_ = None A_ = "strict" A_ = "error" A_ = None def __UpperCAmelCase ( self ): '''simple docstring''' if self.delimiter is not None: __a : Optional[Any] = self.delimiter if self.column_names is not None: __a : Any = self.column_names @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowercase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class __UpperCamelCase ( datasets.ArrowBasedBuilder ): A_ = CsvConfig def __UpperCAmelCase ( self ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) __a : Union[str, Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowercase , (str, list, tuple) ): __a : str = data_files if isinstance(_lowercase , _lowercase ): __a : List[Any] = [files] __a : Union[str, Any] = [dl_manager.iter_files(_lowercase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] __a : Optional[int] = [] for split_name, files in data_files.items(): if isinstance(_lowercase , _lowercase ): __a : Any = [files] __a : Optional[Any] = [dl_manager.iter_files(_lowercase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowercase , gen_kwargs={'files': files} ) ) return splits def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.features is not None: __a : Dict = self.config.features.arrow_schema if all(not require_storage_cast(_lowercase ) for feature in self.config.features.values() ): # cheaper cast __a : str = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowercase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example __a : Tuple = table_cast(_lowercase , _lowercase ) return pa_table def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str __a : Union[str, Any] = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowercase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowercase ) ): __a : Any = pd.read_csv(_lowercase , iterator=_lowercase , dtype=_lowercase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowercase ): __a : Dict = pa.Table.from_pandas(_lowercase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowercase ) except ValueError as e: logger.error(f"""Failed to read file '{file}' with error {type(_lowercase )}: {e}""" ) raise
366
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): re.sub('<n>' , '' , _SCREAMING_SNAKE_CASE ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_SCREAMING_SNAKE_CASE ) )
294
0
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCamelCase_ , unittest.TestCase ): A_ = GPTSanJapaneseTokenizer A_ = False A_ = {"""do_clean_text""": False, """add_prefix_space""": False} def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # fmt: off __a : List[str] = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on __a : Any = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 __a : Optional[Any] = {'unk_token': '<unk>'} __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(_UpperCAmelCase ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Any = 'こんにちは、世界。 \nこんばんは、㔺界。😀' __a : Union[str, Any] = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a , __a : List[str] = self.get_input_output_texts(_UpperCAmelCase ) __a : int = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ) __a : List[str] = tokenizer.decode(_UpperCAmelCase , clean_up_tokenization_spaces=_UpperCAmelCase ) return text, ids def __UpperCAmelCase ( self ): '''simple docstring''' pass # TODO add if relevant def __UpperCAmelCase ( self ): '''simple docstring''' pass # TODO add if relevant def __UpperCAmelCase ( self ): '''simple docstring''' pass # TODO add if relevant def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.get_tokenizer() # Testing tokenization __a : int = 'こんにちは、世界。 こんばんは、㔺界。' __a : Union[str, Any] = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] __a : str = tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) # Testing conversion to ids without special tokens __a : List[Any] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] __a : List[Any] = tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) # Testing conversion to ids with special tokens __a : int = tokens + [tokenizer.unk_token] __a : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] __a : Dict = tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.get_tokenizer() # Testing tokenization __a : Optional[Any] = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' __a : Tuple = 'こんにちは、、、、世界。こんばんは、、、、世界。' __a : Union[str, Any] = tokenizer.encode(_UpperCAmelCase ) __a : Optional[Any] = tokenizer.decode(_UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization __a : int = 'こんにちは、世界。' __a : str = 'こんばんは、㔺界。😀' __a : Optional[int] = 'こんにちは、世界。こんばんは、世界。😀' __a : List[Any] = tokenizer.encode(prefix_text + input_text ) __a : Union[str, Any] = tokenizer.encode('' , prefix_text=prefix_text + input_text ) __a : Tuple = tokenizer.encode(_UpperCAmelCase , prefix_text=_UpperCAmelCase ) __a : Dict = tokenizer.decode(_UpperCAmelCase ) __a : List[str] = tokenizer.decode(_UpperCAmelCase ) __a : Dict = tokenizer.decode(_UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization __a : Optional[Any] = 'こんにちは、世界。' __a : Optional[Any] = 'こんばんは、㔺界。😀' __a : str = len(tokenizer.encode(_UpperCAmelCase ) ) - 2 __a : Optional[Any] = len(tokenizer.encode(_UpperCAmelCase ) ) - 2 __a : int = [1] + [0] * (len_prefix + len_text + 1) __a : Union[str, Any] = [1] * (len_prefix + len_text + 1) + [0] __a : Optional[Any] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) __a : Any = tokenizer(prefix_text + input_text ).token_type_ids __a : List[Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids __a : str = tokenizer(_UpperCAmelCase , prefix_text=_UpperCAmelCase ).token_type_ids self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) __a : Optional[int] = tokenizer.encode('あンいワ' ) __a : Tuple = tokenizer.encode('' , prefix_text='あンいワ' ) __a : List[str] = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(_UpperCAmelCase ) , tokenizer.decode(_UpperCAmelCase ) ) self.assertEqual(tokenizer.decode(_UpperCAmelCase ) , tokenizer.decode(_UpperCAmelCase ) ) self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) __a : Optional[Any] = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] __a : Optional[int] = tokenizer(_UpperCAmelCase , padding=_UpperCAmelCase ) __a : Optional[int] = tokenizer.batch_encode_plus(_UpperCAmelCase , padding=_UpperCAmelCase ) # fmt: off __a : Optional[Any] = [[3_5993, 8640, 2_5948, 3_5998, 3_0647, 3_5675, 3_5999, 3_5999], [3_5993, 1_0382, 9868, 3_5998, 3_0646, 9459, 3_0646, 3_5675]] __a : Union[str, Any] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] __a : List[str] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , _UpperCAmelCase ) self.assertListEqual(x_token.token_type_ids , _UpperCAmelCase ) self.assertListEqual(x_token.attention_mask , _UpperCAmelCase ) self.assertListEqual(x_token_a.input_ids , _UpperCAmelCase ) self.assertListEqual(x_token_a.token_type_ids , _UpperCAmelCase ) self.assertListEqual(x_token_a.attention_mask , _UpperCAmelCase ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' pass
367
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowercase : Any = [0, 25, 50] __lowercase : int = [25, 50, 75] __lowercase : List[str] = fuzz.membership.trimf(X, abca) __lowercase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowercase : List[Any] = np.ones(75) __lowercase : Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowercase : str = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowercase : List[Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowercase : Optional[Any] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowercase : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowercase : Optional[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowercase : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
294
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __UpperCamelCase ( _a ): A_ = 42 A_ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __UpperCamelCase ( _a ): A_ = 42 A_ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
368
'''simple docstring''' import sys __lowercase : Union[str, Any] = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : List[str] = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = N ): __a : Optional[int] = -sys.maxsize - 1 __a : Optional[Any] = n[:13] __a : int = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): __a : List[Any] = substr[1:] + n[cur_index] cur_index += 1 else: __a : Dict = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) __a : Optional[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
294
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = UnCLIPImageVariationPipeline A_ = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"} A_ = IMAGE_VARIATION_BATCH_PARAMS A_ = [ "generator", "return_dict", "decoder_num_inference_steps", "super_res_num_inference_steps", ] A_ = False @property def __UpperCAmelCase ( self ): '''simple docstring''' return 32 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 32 @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCAmelCase ( self ): '''simple docstring''' return 100 @property def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(lowercase_ ) @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(lowercase_ ) @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = { 'clip_embeddings_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'cross_attention_dim': self.cross_attention_dim, } __a : Optional[int] = UnCLIPTextProjModel(**lowercase_ ) return model @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : Any = { 'sample_size': 32, # RGB in channels 'in_channels': 3, # Out channels is double in channels because predicts mean and variance 'out_channels': 6, 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': 'identity', } __a : List[str] = UNetaDConditionModel(**lowercase_ ) return model @property def __UpperCAmelCase ( self ): '''simple docstring''' return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __a : Union[str, Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def __UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(1 ) __a : Union[str, Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.dummy_decoder __a : int = self.dummy_text_proj __a : List[Any] = self.dummy_text_encoder __a : str = self.dummy_tokenizer __a : Tuple = self.dummy_super_res_first __a : List[Any] = self.dummy_super_res_last __a : List[str] = UnCLIPScheduler( variance_type='learned_range' , prediction_type='epsilon' , num_train_timesteps=1000 , ) __a : Optional[int] = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='epsilon' , num_train_timesteps=1000 , ) __a : List[str] = CLIPImageProcessor(crop_size=32 , size=32 ) __a : Optional[Any] = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def __UpperCAmelCase ( self , __a , __a=0 , __a=True ): '''simple docstring''' __a : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) if str(lowercase_ ).startswith('mps' ): __a : Tuple = torch.manual_seed(lowercase_ ) else: __a : int = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) if pil_image: __a : int = input_image * 0.5 + 0.5 __a : Optional[Any] = input_image.clamp(0 , 1 ) __a : List[Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __a : List[Any] = DiffusionPipeline.numpy_to_pil(lowercase_ )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = 'cpu' __a : List[Any] = self.get_dummy_components() __a : str = self.pipeline_class(**lowercase_ ) __a : Dict = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) __a : str = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : str = pipe(**lowercase_ ) __a : str = output.images __a : Tuple = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : List[str] = pipe( **lowercase_ , return_dict=lowercase_ , )[0] __a : List[Any] = image[0, -3:, -3:, -1] __a : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : Dict = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = 'cpu' __a : str = self.get_dummy_components() __a : List[Any] = self.pipeline_class(**lowercase_ ) __a : Optional[int] = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) __a : str = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : List[str] = pipe(**lowercase_ ) __a : List[Any] = output.images __a : int = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : Dict = pipe( **lowercase_ , return_dict=lowercase_ , )[0] __a : Any = image[0, -3:, -3:, -1] __a : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : List[str] = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = 'cpu' __a : Optional[int] = self.get_dummy_components() __a : List[str] = self.pipeline_class(**lowercase_ ) __a : str = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) __a : Optional[Any] = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : List[Any] = [ pipeline_inputs['image'], pipeline_inputs['image'], ] __a : str = pipe(**lowercase_ ) __a : Any = output.images __a : str = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : List[str] = [ tuple_pipeline_inputs['image'], tuple_pipeline_inputs['image'], ] __a : List[Any] = pipe( **lowercase_ , return_dict=lowercase_ , )[0] __a : int = image[0, -3:, -3:, -1] __a : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) __a : str = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = torch.device('cpu' ) class __UpperCamelCase : A_ = 1 __a : int = self.get_dummy_components() __a : Optional[int] = self.pipeline_class(**lowercase_ ) __a : Tuple = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) __a : Union[str, Any] = torch.Generator(device=lowercase_ ).manual_seed(0 ) __a : Union[str, Any] = pipe.decoder.dtype __a : Optional[int] = 1 __a : int = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) __a : str = pipe.prepare_latents( lowercase_ , dtype=lowercase_ , device=lowercase_ , generator=lowercase_ , latents=lowercase_ , scheduler=DummyScheduler() ) __a : Optional[int] = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) __a : Tuple = pipe.prepare_latents( lowercase_ , dtype=lowercase_ , device=lowercase_ , generator=lowercase_ , latents=lowercase_ , scheduler=DummyScheduler() ) __a : Any = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) __a : Dict = pipe( **lowercase_ , decoder_latents=lowercase_ , super_res_latents=lowercase_ ).images __a : List[Any] = self.get_dummy_inputs(lowercase_ , pil_image=lowercase_ ) # Don't pass image, instead pass embedding __a : List[str] = pipeline_inputs.pop('image' ) __a : Tuple = pipe.image_encoder(lowercase_ ).image_embeds __a : Tuple = pipe( **lowercase_ , decoder_latents=lowercase_ , super_res_latents=lowercase_ , image_embeddings=lowercase_ , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = torch_device == 'cpu' # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor __a : Dict = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=lowercase_ , expected_max_diff=lowercase_ ) @skip_mps def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = torch_device == 'cpu' __a : Tuple = True __a : Optional[int] = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] self._test_inference_batch_single_identical( test_max_difference=lowercase_ , relax_max_difference=lowercase_ , additional_params_copy_to_batched_inputs=lowercase_ , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes __a : Optional[int] = [2, 3] self._test_inference_batch_consistent( batch_sizes=lowercase_ , additional_params_copy_to_batched_inputs=lowercase_ , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=lowercase_ ) @skip_mps def __UpperCAmelCase ( self ): '''simple docstring''' return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCAmelCase ( self ): '''simple docstring''' return super().test_save_load_local() @skip_mps def __UpperCAmelCase ( self ): '''simple docstring''' return super().test_save_load_optional_components() @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png' ) __a : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/unclip/karlo_v1_alpha_cat_variation_fp16.npy' ) __a : str = UnCLIPImageVariationPipeline.from_pretrained( 'kakaobrain/karlo-v1-alpha-image-variations' , torch_dtype=torch.floataa ) __a : str = pipeline.to(lowercase_ ) pipeline.set_progress_bar_config(disable=lowercase_ ) __a : Union[str, Any] = torch.Generator(device='cpu' ).manual_seed(0 ) __a : List[str] = pipeline( lowercase_ , generator=lowercase_ , output_type='np' , ) __a : Union[str, Any] = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(lowercase_ , lowercase_ , 15 )
369
'''simple docstring''' import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = CodeGenTokenizer A_ = CodeGenTokenizerFast A_ = True A_ = {"add_prefix_space": True} A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __a : Tuple = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __a : Union[str, Any] = dict(zip(__a , range(len(__a ) ) ) ) __a : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : Dict = {'unk_token': '<unk>'} __a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__a ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = 'lower newer' __a : Tuple = 'lower newer' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __a : str = 'lower newer' __a : Tuple = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) self.assertListEqual(__a , __a ) __a : List[str] = tokens + [tokenizer.unk_token] __a : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Any = 'lower newer' # Testing tokenization __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) __a : Dict = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids without special tokens __a : int = tokenizer.encode(__a , add_special_tokens=__a , add_prefix_space=__a ) __a : Tuple = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids with special tokens __a : Tuple = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Union[str, Any] = tokenizer.encode(__a , add_prefix_space=__a ) __a : int = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # Testing the unknown token __a : Any = tokens + [rust_tokenizer.unk_token] __a : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' pass def __UpperCAmelCase ( self , __a=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : Optional[int] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) # Simple input __a : List[Any] = 'This is a simple input' __a : Tuple = ['This is a simple input 1', 'This is a simple input 2'] __a : Tuple = ('This is a simple input', 'This is a pair') __a : str = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) # Pair input self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __a : str = 'This is a simple input' __a : Any = ['This is a simple input looooooooong', 'This is a simple input'] __a : Optional[int] = ('This is a simple input', 'This is a pair') __a : Optional[Any] = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __a : int = tokenizer.pad_token_id __a : List[Any] = tokenizer(__a , padding='max_length' , max_length=30 , return_tensors='np' ) __a : Union[str, Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) __a : Optional[Any] = tokenizer(*__a , padding='max_length' , max_length=60 , return_tensors='np' ) __a : List[Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = '$$$' __a : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__a , add_bos_token=__a ) __a : Union[str, Any] = 'This is a simple input' __a : List[Any] = ['This is a simple input 1', 'This is a simple input 2'] __a : List[Any] = tokenizer.bos_token_id __a : List[str] = tokenizer(__a ) __a : Optional[Any] = tokenizer(__a ) self.assertEqual(out_s.input_ids[0] , __a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __a : Any = tokenizer.decode(out_s.input_ids ) __a : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' ) __a : Optional[int] = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' __a : Tuple = '\nif len_a > len_b: result = a\nelse: result = b' __a : Optional[int] = tokenizer.encode(__a ) __a : Union[str, Any] = ['^#', re.escape('<|endoftext|>' ), '^\'\'\'', '^"""', '\n\n\n'] __a : Tuple = tokenizer.decode(__a , truncate_before_pattern=__a ) self.assertEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' pass
294
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : List[str] = logging.get_logger(__name__) __lowercase : int = { 'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json', 'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json', 'uclanlp/visualbert-vqa-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json', 'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json', 'uclanlp/visualbert-vcr-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class __UpperCamelCase ( a__ ): A_ = "visual_bert" def __init__( self , __a=3_0522 , __a=768 , __a=512 , __a=12 , __a=12 , __a=3072 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=2 , __a=0.02 , __a=1E-1_2 , __a=False , __a=True , __a=1 , __a=0 , __a=2 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Optional[int] = vocab_size __a : str = max_position_embeddings __a : str = hidden_size __a : Union[str, Any] = visual_embedding_dim __a : Any = num_hidden_layers __a : Union[str, Any] = num_attention_heads __a : Optional[Any] = intermediate_size __a : List[Any] = hidden_act __a : Optional[int] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : List[str] = type_vocab_size __a : str = layer_norm_eps __a : List[str] = bypass_transformer __a : Optional[int] = special_visual_initialize
370
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError('iterations must be defined as integers' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) __a : Dict = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_SCREAMING_SNAKE_CASE ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowercase : List[str] = logging.get_logger(__name__) __lowercase : Union[str, Any] = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): A_ = "nat" A_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , __a=4 , __a=3 , __a=64 , __a=[3, 4, 6, 5] , __a=[2, 4, 8, 16] , __a=7 , __a=3.0 , __a=True , __a=0.0 , __a=0.0 , __a=0.1 , __a="gelu" , __a=0.02 , __a=1E-5 , __a=0.0 , __a=None , __a=None , **__a , ): '''simple docstring''' super().__init__(**_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = patch_size __a : Optional[int] = num_channels __a : Any = embed_dim __a : List[Any] = depths __a : str = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = num_heads __a : Optional[int] = kernel_size __a : int = mlp_ratio __a : Optional[int] = qkv_bias __a : Union[str, Any] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : Dict = drop_path_rate __a : str = hidden_act __a : Any = layer_norm_eps __a : Dict = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __a : int = int(embed_dim * 2 ** (len(_SCREAMING_SNAKE_CASE ) - 1) ) __a : Optional[Any] = layer_scale_init_value __a : Union[str, Any] = ['''stem'''] + [f"""stage{idx}""" for idx in range(1 , len(_SCREAMING_SNAKE_CASE ) + 1 )] __a : Union[str, Any] = get_aligned_output_features_output_indices( out_features=_SCREAMING_SNAKE_CASE , out_indices=_SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
371
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , ): '''simple docstring''' __a : List[Any] = size if size is not None else {'height': 18, 'width': 18} __a : int = parent __a : Dict = batch_size __a : Optional[int] = num_channels __a : List[Any] = image_size __a : Tuple = min_resolution __a : str = max_resolution __a : str = do_resize __a : Optional[Any] = size __a : str = apply_ocr def __UpperCAmelCase ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LayoutLMvaImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'apply_ocr' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __a : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched __a : Any = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : Tuple = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __a : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : List[str] = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __a : str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) __a : Tuple = Image.open(ds[0]['file'] ).convert('RGB' ) __a : Optional[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a : Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 __a : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False __a : List[Any] = LayoutLMvaImageProcessor(apply_ocr=__a ) __a : List[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
294
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: __lowercase : str = None __lowercase : Optional[Any] = logging.get_logger(__name__) __lowercase : Optional[int] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __lowercase : Union[str, Any] = { "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", }, "tokenizer_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/tokenizer.json", }, } __lowercase : List[str] = { "camembert-base": 5_12, } __lowercase : int = "▁" class __UpperCamelCase ( a_ ): A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ = ["input_ids", "attention_mask"] A_ = CamembertTokenizer def __init__( self , __a=None , __a=None , __a="<s>" , __a="</s>" , __a="</s>" , __a="<s>" , __a="<unk>" , __a="<pad>" , __a="<mask>" , __a=["<s>NOTUSED", "</s>NOTUSED"] , **__a , ): '''simple docstring''' __a : List[Any] = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token super().__init__( __a , tokenizer_file=__a , bos_token=__a , eos_token=__a , sep_token=__a , cls_token=__a , unk_token=__a , pad_token=__a , mask_token=__a , additional_special_tokens=__a , **__a , ) __a : Union[str, Any] = vocab_file __a : Dict = False if not self.vocab_file else True def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a : Dict = [self.cls_token_id] __a : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : str = [self.sep_token_id] __a : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(__a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : List[Any] = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ): copyfile(self.vocab_file , __a ) return (out_vocab_file,)
350
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any=28_123 ): __a : Tuple = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i __a : Union[str, Any] = set() __a : Dict = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(_SCREAMING_SNAKE_CASE ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
351
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a ): '''simple docstring''' super().__init__() __a : int = module __a : List[Any] = nn.Sequential( nn.Linear(module.in_features , __a , bias=__a ) , nn.Linear(__a , module.out_features , bias=__a ) , ) __a : int = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=__a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' return self.module(__a , *__a , **__a ) + self.adapter(__a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module A_ = "bigscience/bloom-1b7" # Constant values A_ = 2.109659552692574 A_ = "Hello my name is" A_ = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) A_ = 10 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = AutoTokenizer.from_pretrained(self.model_name ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Models and tokenizer __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_abit.config self.assertTrue(hasattr(__a , 'quantization_config' ) ) __a : Union[str, Any] = config.to_dict() __a : Tuple = config.to_diff_dict() __a : Tuple = config.to_json_string() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit __a : List[Any] = self.model_fpaa.get_memory_footprint() __a : List[Any] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __a : Tuple = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(__a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Union[str, Any] = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BitsAndBytesConfig() __a : Tuple = True __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ) __a : List[Any] = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = BitsAndBytesConfig() with self.assertRaises(__a ): __a : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , load_in_abit=__a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(__a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(__a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __a : List[str] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Optional[int] = self.model_fpaa.to(torch.floataa ) __a : Tuple = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __a : List[Any] = self.model_fpaa.to('cpu' ) # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.half() # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.float() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=__a , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' __a : Any = 't5-small' __a : Tuple = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __a : int = AutoTokenizer.from_pretrained(cls.model_name ) __a : Union[str, Any] = 'Translate in German: Hello, my dog is cute' def __UpperCAmelCase ( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaForConditionalGeneration __a : Optional[int] = TaForConditionalGeneration._keep_in_fpaa_modules __a : List[str] = None # test with `t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[int] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : Any = model.generate(**__a ) # test with `flan-t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[Any] = model.generate(**__a ) __a : Optional[int] = modules def __UpperCAmelCase ( self ): '''simple docstring''' import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[str] = model.generate(**__a ) # test with `flan-t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : int = model.generate(**__a ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # model_name __a : List[Any] = 'bigscience/bloom-560m' __a : Union[str, Any] = 't5-small' # Different types of model __a : Optional[Any] = AutoModel.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Sequence classification model __a : Dict = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=__a , device_map='auto' ) # CausalLM model __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Seq2seq model __a : Any = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' del self.pipe gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __a : str = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=__a , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __a : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __a : str = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'facebook/opt-350m' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __a : Tuple = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __a : Tuple = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(__a ) ): __a : str = LoRALayer(module.q_proj , rank=16 ) __a : str = LoRALayer(module.k_proj , rank=16 ) __a : Optional[int] = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __a : List[str] = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __a : int = model.forward(**__a ) out.logits.norm().backward() for module in model.modules(): if isinstance(__a , __a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(__a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "gpt2-xl" A_ = 3.3191854854152187
294
0
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowercase : List[Any] = 16 __lowercase : Tuple = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : DatasetDict , _SCREAMING_SNAKE_CASE : List[int] , _SCREAMING_SNAKE_CASE : List[int] , _SCREAMING_SNAKE_CASE : int = 16 ): __a : Optional[Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) __a : Union[str, Any] = DatasetDict( { 'train': dataset['train'].select(UpperCamelCase__ ), 'validation': dataset['train'].select(UpperCamelCase__ ), 'test': dataset['validation'], } ) def tokenize_function(_SCREAMING_SNAKE_CASE : Union[str, Any] ): # max_length=None => use the model max length (it's actually the default) __a : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __a : str = datasets.map( UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : int = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. __a : Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __a : int = 16 elif accelerator.mixed_precision != "no": __a : List[str] = 8 else: __a : Optional[int] = None return tokenizer.pad( UpperCamelCase__ , padding='longest' , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors='pt' , ) # Instantiate dataloaders. __a : Optional[int] = DataLoader( tokenized_datasets['train'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) __a : Any = DataLoader( tokenized_datasets['validation'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) __a : Union[str, Any] = DataLoader( tokenized_datasets['test'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple ): # New Code # __a : Optional[Any] = [] # Download the dataset __a : str = load_dataset('glue' , 'mrpc' ) # Create our splits __a : Optional[Any] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator __a : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : List[str] = config['''lr'''] __a : Union[str, Any] = int(config['num_epochs'] ) __a : Dict = int(config['seed'] ) __a : Optional[int] = int(config['batch_size'] ) __a : List[str] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation __a : Union[str, Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __a : str = batch_size // MAX_GPU_BATCH_SIZE __a : Dict = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) # New Code # # Create our folds: __a : Optional[Any] = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) __a : str = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(UpperCamelCase__ ): __a : int = get_fold_dataloaders( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Optional[Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=UpperCamelCase__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __a : List[Any] = model.to(accelerator.device ) # Instantiate optimizer __a : int = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler __a : Tuple = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a : Dict = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __a : Optional[Any] = model(**UpperCamelCase__ ) __a : List[Any] = outputs.loss __a : Dict = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a : int = model(**UpperCamelCase__ ) __a : Optional[int] = outputs.logits.argmax(dim=-1 ) __a : Optional[Any] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) __a : Any = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) # New Code # # We also run predictions on the test set at the very end __a : int = [] for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a : List[Any] = model(**UpperCamelCase__ ) __a : Dict = outputs.logits __a : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(UpperCamelCase__ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: __a : Tuple = torch.cat(UpperCamelCase__ , dim=0 ) __a : List[str] = torch.stack(UpperCamelCase__ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) __a : List[Any] = metric.compute(predictions=UpperCamelCase__ , references=UpperCamelCase__ ) accelerator.print('Average test metrics from all folds:' , UpperCamelCase__ ) def lowerCamelCase (): __a : List[str] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=UpperCamelCase__ , default=3 , help='The number of splits to perform across the dataset' ) __a : Tuple = parser.parse_args() __a : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
352
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAmelCase_ ): A_ = None A_ = None A_ = None A_ = None class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a=1 , __a=0 , __a=2 , __a=512 , __a="cls" , __a=False , __a=True , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Any = project_dim __a : Optional[Any] = pooler_fn __a : int = learn_encoder __a : str = use_attention_mask class __UpperCamelCase ( lowerCAmelCase_ ): A_ = [r"pooler", r"logit_scale"] A_ = [r"position_ids", r"predictions.decoder.bias"] A_ = "roberta" A_ = RobertaSeriesConfig def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Optional[Any] = XLMRobertaModel(__a ) __a : str = nn.Linear(config.hidden_size , config.project_dim ) __a : Optional[int] = getattr(__a , 'has_pre_transformation' , __a ) if self.has_pre_transformation: __a : int = nn.Linear(config.hidden_size , config.project_dim ) __a : List[str] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Tuple = self.base_model( input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , ) if self.has_pre_transformation: __a : Optional[Any] = outputs['hidden_states'][-2] __a : Optional[int] = self.pre_LN(__a ) __a : Union[str, Any] = self.transformation_pre(__a ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __a : Optional[Any] = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
294
0
'''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 __UpperCamelCase ( _lowerCamelCase , _lowerCamelCase ): @register_to_config def __init__( self , __a = 768 , ): '''simple docstring''' super().__init__() __a : Any = nn.Parameter(torch.zeros(1 , __a ) ) __a : Optional[int] = nn.Parameter(torch.ones(1 , __a ) ) def __UpperCAmelCase ( self , __a = None , __a = None , ): '''simple docstring''' __a : Optional[int] = nn.Parameter(self.mean.to(__a ).to(__a ) ) __a : Optional[Any] = nn.Parameter(self.std.to(__a ).to(__a ) ) return self def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : List[str] = (embeds - self.mean) * 1.0 / self.std return embeds def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : List[Any] = (embeds * self.std) + self.mean return embeds
353
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename __lowercase : List[Any] = '''http://www.mocksite.com/file1.txt''' __lowercase : Optional[int] = '''"text": ["foo", "foo"]''' __lowercase : int = '''6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8''' class __UpperCamelCase : A_ = 200 A_ = {"Content-Length": "100"} A_ = {} def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return [bytes(__a , 'utf-8' )] def lowerCamelCase (*_SCREAMING_SNAKE_CASE : Any , **_SCREAMING_SNAKE_CASE : List[Any] ): return MockResponse() @pytest.mark.parametrize('urls_type' , [str, list, dict] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): import requests monkeypatch.setattr(_lowerCAmelCase , 'request' , _lowerCAmelCase ) __a : Optional[Any] = URL if issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : List[Any] = url elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : List[Any] = [url] elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : Tuple = {"train": url} __a : List[str] = "dummy" __a : Union[str, Any] = "downloads" __a : Union[str, Any] = tmp_path __a : str = DownloadConfig( cache_dir=os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , use_etag=_lowerCAmelCase , ) __a : str = DownloadManager(dataset_name=_lowerCAmelCase , download_config=_lowerCAmelCase ) __a : Tuple = dl_manager.download(_lowerCAmelCase ) __a : List[Any] = urls for downloaded_paths in [downloaded_paths]: if isinstance(_lowerCAmelCase , _lowerCAmelCase ): __a : List[Any] = [downloaded_paths] __a : Optional[Any] = [urls] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): assert "train" in downloaded_paths.keys() __a : Any = downloaded_paths.values() __a : str = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(_lowerCAmelCase , _lowerCAmelCase ): assert downloaded_path == dl_manager.downloaded_paths[input_url] __a : Tuple = Path(_lowerCAmelCase ) __a : List[str] = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() __a : Any = downloaded_path.read_text() assert content == CONTENT __a : Optional[Any] = downloaded_path.with_suffix('.json' ) assert metadata_downloaded_path.exists() __a : Optional[Any] = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize('paths_type' , [str, list, dict] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any ): __a : Tuple = str(_lowerCAmelCase ) if issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : Union[str, Any] = filename elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : Optional[int] = [filename] elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): __a : List[Any] = {"train": filename} __a : str = "dummy" __a : Dict = xz_file.parent __a : Any = "extracted" __a : Union[str, Any] = DownloadConfig( cache_dir=_lowerCAmelCase , use_etag=_lowerCAmelCase , ) __a : int = DownloadManager(dataset_name=_lowerCAmelCase , download_config=_lowerCAmelCase ) __a : Optional[int] = dl_manager.extract(_lowerCAmelCase ) __a : Union[str, Any] = paths for extracted_paths in [extracted_paths]: if isinstance(_lowerCAmelCase , _lowerCAmelCase ): __a : List[str] = [extracted_paths] __a : List[str] = [paths] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): assert "train" in extracted_paths.keys() __a : Any = extracted_paths.values() __a : Optional[int] = paths.values() assert extracted_paths for extracted_path, input_path in zip(_lowerCAmelCase , _lowerCAmelCase ): assert extracted_path == dl_manager.extracted_paths[input_path] __a : Union[str, Any] = Path(_lowerCAmelCase ) __a : Optional[int] = extracted_path.parts assert parts[-1] == hash_url_to_filename(_lowerCAmelCase , etag=_lowerCAmelCase ) assert parts[-2] == extracted_subdir assert extracted_path.exists() __a : Optional[int] = extracted_path.read_text() __a : Union[str, Any] = text_file.read_text() assert extracted_file_content == expected_file_content def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Dict ): assert path.endswith('.jsonl' ) for num_items, line in enumerate(_lowerCAmelCase , start=1 ): __a : Any = json.loads(line.decode('utf-8' ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize('archive_jsonl' , ['tar_jsonl_path', 'zip_jsonl_path'] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): __a : Dict = request.getfixturevalue(_lowerCAmelCase ) __a : Tuple = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): _test_jsonl(_lowerCAmelCase , _lowerCAmelCase ) assert num_jsonl == 2 @pytest.mark.parametrize('archive_nested_jsonl' , ['tar_nested_jsonl_path', 'zip_nested_jsonl_path'] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any ): __a : List[str] = request.getfixturevalue(_lowerCAmelCase ) __a : List[str] = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(_lowerCAmelCase ) , start=1 ): _test_jsonl(_lowerCAmelCase , _lowerCAmelCase ) assert num_tar == 1 assert num_jsonl == 2 def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(_lowerCAmelCase ) , start=1 ): assert os.path.basename(_lowerCAmelCase ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __lowercase : str = logging.get_logger(__name__) # General docstring __lowercase : List[str] = 'MobileNetV1Config' # Base docstring __lowercase : Tuple = 'google/mobilenet_v1_1.0_224' __lowercase : List[Any] = [1, 10_24, 7, 7] # Image classification docstring __lowercase : int = 'google/mobilenet_v1_1.0_224' __lowercase : Any = 'tabby, tabby cat' __lowercase : Dict = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any]=None ): __a : Dict = {} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = model.mobilenet_va else: __a : List[Any] = model __a : Dict = 'MobilenetV1/Conv2d_0/' __a : Dict = backbone.conv_stem.convolution.weight __a : Optional[Any] = backbone.conv_stem.normalization.bias __a : int = backbone.conv_stem.normalization.weight __a : int = backbone.conv_stem.normalization.running_mean __a : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): __a : int = i + 1 __a : Dict = i * 2 __a : Dict = backbone.layer[pt_index] __a : Dict = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" __a : Union[str, Any] = pointer.convolution.weight __a : Optional[Any] = pointer.normalization.bias __a : Union[str, Any] = pointer.normalization.weight __a : List[Any] = pointer.normalization.running_mean __a : Tuple = pointer.normalization.running_var __a : List[str] = backbone.layer[pt_index + 1] __a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" __a : Optional[int] = pointer.convolution.weight __a : List[str] = pointer.normalization.bias __a : Dict = pointer.normalization.weight __a : Dict = pointer.normalization.running_mean __a : Optional[int] = pointer.normalization.running_var if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Any = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __a : Optional[int] = model.classifier.weight __a : List[Any] = model.classifier.bias return tf_to_pt_map def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __a : Union[str, Any] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) __a : List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = array # Build TF to PyTorch weights loading map __a : Optional[int] = _build_tf_to_pytorch_map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue __a : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __a : Optional[Any] = np.transpose(_SCREAMING_SNAKE_CASE , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __a : Union[str, Any] = array.squeeze().transpose() else: __a : Dict = np.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) __a : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) tf_weights.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp_1' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/ExponentialMovingAverage' , _SCREAMING_SNAKE_CASE ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def lowerCamelCase (_SCREAMING_SNAKE_CASE : torch.Tensor , _SCREAMING_SNAKE_CASE : nn.Convad ): __a , __a : Any = features.shape[-2:] __a , __a : int = conv_layer.stride __a , __a : Any = conv_layer.kernel_size if in_height % stride_height == 0: __a : int = max(kernel_height - stride_height , 0 ) else: __a : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __a : Any = max(kernel_width - stride_width , 0 ) else: __a : str = max(kernel_width - (in_width % stride_width) , 0 ) __a : int = pad_along_width // 2 __a : Dict = pad_along_width - pad_left __a : List[str] = pad_along_height // 2 __a : Union[str, Any] = pad_along_height - pad_top __a : str = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'constant' , 0.0 ) class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a , __a , __a , __a = 1 , __a = 1 , __a = False , __a = True , __a = True , ): '''simple docstring''' super().__init__() __a : Optional[int] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) __a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __a : Union[str, Any] = nn.Convad( in_channels=__a , out_channels=__a , kernel_size=__a , stride=__a , padding=__a , groups=__a , bias=__a , padding_mode='zeros' , ) if use_normalization: __a : List[str] = nn.BatchNormad( num_features=__a , eps=config.layer_norm_eps , momentum=0.9997 , affine=__a , track_running_stats=__a , ) else: __a : Tuple = None if use_activation: if isinstance(__a , __a ): __a : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , __a ): __a : Union[str, Any] = ACTaFN[config.hidden_act] else: __a : Dict = config.hidden_act else: __a : List[Any] = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.tf_padding: __a : Union[str, Any] = apply_tf_padding(__a , self.convolution ) __a : Union[str, Any] = self.convolution(__a ) if self.normalization is not None: __a : str = self.normalization(__a ) if self.activation is not None: __a : Optional[int] = self.activation(__a ) return features class __UpperCamelCase ( lowerCAmelCase_ ): A_ = MobileNetVaConfig A_ = load_tf_weights_in_mobilenet_va A_ = "mobilenet_v1" A_ = "pixel_values" A_ = False def __UpperCAmelCase ( self , __a ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __lowercase : Any = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowercase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a = True ): '''simple docstring''' super().__init__(__a ) __a : Optional[int] = config __a : str = 32 __a : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) __a : Union[str, Any] = MobileNetVaConvLayer( __a , in_channels=config.num_channels , out_channels=__a , kernel_size=3 , stride=2 , ) __a : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __a : Any = nn.ModuleList() for i in range(13 ): __a : Union[str, Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 __a : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=3 , stride=strides[i] , groups=__a , ) ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=1 , ) ) __a : Optional[int] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __UpperCAmelCase ( self , __a ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a : int = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __a : Union[str, Any] = self.conv_stem(__a ) __a : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __a : List[str] = layer_module(__a ) if output_hidden_states: __a : List[Any] = all_hidden_states + (hidden_states,) __a : str = hidden_states if self.pooler is not None: __a : Union[str, Any] = torch.flatten(self.pooler(__a ) , start_dim=1 ) else: __a : int = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__a , pooler_output=__a , hidden_states=__a , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Tuple = config.num_labels __a : Tuple = MobileNetVaModel(__a ) __a : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __a : Any = nn.Dropout(config.classifier_dropout_prob , inplace=__a ) __a : Any = nn.Linear(__a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Dict = self.mobilenet_va(__a , output_hidden_states=__a , return_dict=__a ) __a : List[str] = outputs.pooler_output if return_dict else outputs[1] __a : int = self.classifier(self.dropout(__a ) ) __a : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a : int = 'single_label_classification' else: __a : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __a : Optional[Any] = MSELoss() if self.num_labels == 1: __a : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __a : List[str] = CrossEntropyLoss() __a : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a : Tuple = BCEWithLogitsLoss() __a : Optional[int] = loss_fct(__a , __a ) if not return_dict: __a : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=__a , logits=__a , hidden_states=outputs.hidden_states , )
294
0
import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/grid.txt' ) as f: __a : Tuple = [] # noqa: E741 for _ in range(20 ): l.append([int(_SCREAMING_SNAKE_CASE ) for x in f.readline().split()] ) __a : Tuple = 0 # right for i in range(20 ): for j in range(17 ): __a : Optional[int] = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: __a : Optional[int] = temp # down for i in range(17 ): for j in range(20 ): __a : str = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: __a : Union[str, Any] = temp # diagonal 1 for i in range(17 ): for j in range(17 ): __a : Dict = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: __a : Optional[int] = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): __a : Tuple = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: __a : Tuple = temp return maximum if __name__ == "__main__": print(solution())
355
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase : str = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "dhaka" , _SCREAMING_SNAKE_CASE : int = 5 ): __a : Optional[Any] = min(_SCREAMING_SNAKE_CASE , 50 ) # Prevent abuse! __a : Optional[Any] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } __a : Tuple = requests.get('https://www.google.com/search' , params=_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ) __a : Dict = BeautifulSoup(html.text , 'html.parser' ) __a : List[str] = ''.join( re.findall(r'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) __a : Optional[Any] = json.dumps(_SCREAMING_SNAKE_CASE ) __a : List[str] = json.loads(_SCREAMING_SNAKE_CASE ) __a : List[Any] = re.findall( r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , _SCREAMING_SNAKE_CASE , ) if not matched_google_image_data: return 0 __a : Tuple = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(_SCREAMING_SNAKE_CASE ) , ) __a : Optional[Any] = re.findall( r'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , _SCREAMING_SNAKE_CASE , ) for index, fixed_full_res_image in enumerate(_SCREAMING_SNAKE_CASE ): if index >= max_images: return index __a : List[str] = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Tuple = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Dict = urllib.request.build_opener() __a : Union[str, Any] = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(_SCREAMING_SNAKE_CASE ) __a : List[Any] = F"""query_{query.replace(" " , "_" )}""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): os.makedirs(_SCREAMING_SNAKE_CASE ) urllib.request.urlretrieve( # noqa: S310 _SCREAMING_SNAKE_CASE , F"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: __lowercase : Optional[int] = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print('Please provide a search term.') raise
294
0
'''simple docstring''' from datetime import datetime import requests def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : List[str] = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' __a : Optional[Any] = requests.get(base_url + url ).json()[0]['urls'][0]['src'] return requests.get(__UpperCAmelCase ).content if __name__ == "__main__": __lowercase : Optional[Any] = input('Enter Video/IGTV url: ').strip() __lowercase : Union[str, Any] = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split(',' ) names.sort() __a : Union[str, Any] = 0 __a : Tuple = 0 for i, name in enumerate(_SCREAMING_SNAKE_CASE ): for letter in name: name_score += ord(_SCREAMING_SNAKE_CASE ) - 64 total_score += (i + 1) * name_score __a : Any = 0 return total_score if __name__ == "__main__": print(solution())
294
0
'''simple docstring''' __lowercase : List[str] = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : List[Any] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution __lowercase : list[bool | None] = [None] * 10_00_00_00 __lowercase : Optional[Any] = True __lowercase : Optional[int] = False def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore __a : Tuple = chain(next_number(lowercase_ ) ) __a : int = number_chain while number < 10_000_000: __a : Optional[Any] = number_chain number *= 10 return number_chain def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 10_000_000 ): for i in range(1 , lowercase_ ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(lowercase_ ) if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution() = }''')
357
'''simple docstring''' __lowercase : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __lowercase : List[str] = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] ): __a : Any = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : Dict = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: __a : List[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __lowercase : Union[str, Any] = topological_sort('a', [], []) print(sort)
294
0
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : Optional[Any] = 16 __lowercase : Dict = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] = 16 , _SCREAMING_SNAKE_CASE : List[Any] = "bert-base-cased" ): __a : Union[str, Any] = AutoTokenizer.from_pretrained(A_ ) __a : Union[str, Any] = load_dataset('glue' , 'mrpc' ) def tokenize_function(_SCREAMING_SNAKE_CASE : str ): # max_length=None => use the model max length (it's actually the default) __a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=A_ , max_length=A_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __a : List[Any] = datasets.map( A_ , batched=A_ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=A_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : Union[str, Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A_ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(A_ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __a : Optional[Any] = DataLoader( tokenized_datasets['train'] , shuffle=A_ , collate_fn=A_ , batch_size=A_ ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=A_ , collate_fn=A_ , batch_size=A_ ) return train_dataloader, eval_dataloader def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any ): # Initialize accelerator __a : Optional[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : Optional[int] = config['''lr'''] __a : Optional[int] = int(config['num_epochs'] ) __a : List[Any] = int(config['seed'] ) __a : Optional[int] = int(config['batch_size'] ) __a : Union[str, Any] = args.model_name_or_path set_seed(A_ ) __a : Optional[int] = get_dataloaders(A_ , A_ , A_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : List[Any] = AutoModelForSequenceClassification.from_pretrained(A_ , return_dict=A_ ) # Instantiate optimizer __a : List[str] = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a : Tuple = optimizer_cls(params=model.parameters() , lr=A_ ) if accelerator.state.deepspeed_plugin is not None: __a : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: __a : Any = 1 __a : str = (len(A_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __a : Dict = get_linear_schedule_with_warmup( optimizer=A_ , num_warmup_steps=0 , num_training_steps=A_ , ) else: __a : Any = DummyScheduler(A_ , total_num_steps=A_ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a : int = accelerator.prepare( A_ , A_ , A_ , A_ , A_ ) # We need to keep track of how many total steps we have iterated over __a : Tuple = 0 # We also need to keep track of the stating epoch so files are named properly __a : int = 0 # Now we train the model __a : Tuple = evaluate.load('glue' , 'mrpc' ) __a : Dict = 0 __a : Any = {} for epoch in range(A_ , A_ ): model.train() for step, batch in enumerate(A_ ): __a : Optional[Any] = model(**A_ ) __a : List[Any] = outputs.loss __a : str = loss / gradient_accumulation_steps accelerator.backward(A_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() __a : Union[str, Any] = 0 for step, batch in enumerate(A_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a : int = model(**A_ ) __a : int = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __a : Optional[Any] = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(A_ ) - 1: __a : List[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] __a : Dict = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=A_ , references=A_ , ) __a : Optional[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , A_ ) __a : Optional[int] = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: __a : str = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(A_ , A_ ) def lowerCamelCase (): __a : Tuple = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=A_ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=A_ , ) parser.add_argument( '--output_dir' , type=A_ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=A_ , default=A_ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=A_ , default=3 , help='Number of train epochs.' , ) __a : int = parser.parse_args() __a : Any = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(A_ , A_ ) if __name__ == "__main__": main()
358
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] ): if len(_lowercase ) != len(_lowercase ): raise ValueError('The length of profit and weight must be same.' ) if max_weight <= 0: raise ValueError('max_weight must greater than zero.' ) if any(p < 0 for p in profit ): raise ValueError('Profit can not be negative.' ) if any(w < 0 for w in weight ): raise ValueError('Weight can not be negative.' ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. __a : Optional[int] = [p / w for p, w in zip(_lowercase , _lowercase )] # Creating a copy of the list and sorting profit/weight in ascending order __a : List[str] = sorted(_lowercase ) # declaring useful variables __a : Tuple = len(_lowercase ) __a : Any = 0 __a : Optional[Any] = 0 __a : Union[str, Any] = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight __a : str = sorted_profit_by_weight[length - i - 1] __a : List[str] = profit_by_weight.index(_lowercase ) __a : Dict = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( 'Input profits, weights, and then max_weight (all positive ints) separated by ' 'spaces.' ) __lowercase : List[Any] = [int(x) for x in input('Input profits separated by spaces: ').split()] __lowercase : Tuple = [int(x) for x in input('Input weights separated by spaces: ').split()] __lowercase : Union[str, Any] = int(input('Max weight allowed: ')) # Function Call calc_profit(profit, weight, max_weight)
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : str = parent __a : Dict = batch_size __a : str = seq_length __a : Optional[Any] = is_training __a : Union[str, Any] = use_input_mask __a : int = use_token_type_ids __a : Union[str, Any] = use_labels __a : int = vocab_size __a : Optional[Any] = hidden_size __a : Dict = num_hidden_layers __a : Optional[int] = num_attention_heads __a : List[Any] = intermediate_size __a : List[Any] = hidden_act __a : Tuple = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : int = max_position_embeddings __a : Tuple = type_vocab_size __a : List[Any] = type_sequence_label_size __a : Optional[int] = initializer_range __a : int = num_labels __a : str = num_choices __a : int = relative_attention __a : Dict = position_biased_input __a : Tuple = pos_att_type __a : Optional[Any] = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : int = None if self.use_input_mask: __a : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) __a : List[Any] = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[Any] = None __a : str = None __a : Any = None if self.use_labels: __a : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : Tuple = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = TFDebertaVaModel(config=_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} __a : Optional[Any] = [input_ids, input_mask] __a : Optional[int] = model(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = TFDebertaVaForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __a : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __a : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = self.num_labels __a : List[Any] = TFDebertaVaForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __a : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __a : Dict = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = self.num_labels __a : Optional[Any] = TFDebertaVaForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __a : str = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __a : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = TFDebertaVaForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __a : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __a : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.prepare_config_and_inputs() ( __a ) : Optional[int] = config_and_inputs __a : int = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __UpperCamelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): A_ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) A_ = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = TFDebertaVaModelTester(self ) __a : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_tf class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) __a : Tuple = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : int = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __a : Optional[int] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE )[0] __a : List[str] = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
360
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = 'laion/clap-htsat-unfused' __a : Optional[Any] = tempfile.mkdtemp() def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.get_tokenizer() __a : List[str] = self.get_feature_extractor() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) __a : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __a : List[str] = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) __a : Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : int = self.get_tokenizer() __a : str = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : int = floats_list((3, 1000) ) __a : str = feature_extractor(__a , return_tensors='np' ) __a : int = processor(audios=__a , 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 __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.get_feature_extractor() __a : Any = self.get_tokenizer() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Union[str, Any] = 'This is a test string' __a : Union[str, Any] = processor(text=__a ) __a : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : str = self.get_tokenizer() __a : List[str] = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a : Optional[int] = processor.batch_decode(__a ) __a : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.get_feature_extractor() __a : Optional[int] = self.get_tokenizer() __a : int = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
294
0
'''simple docstring''' from math import factorial def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 100 ): return sum(map(_a , str(factorial(_a ) ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
361
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : List[str] = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : List[str] = num_hidden_layers __a : str = num_attention_heads __a : Optional[int] = intermediate_size __a : Tuple = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[int] = max_position_embeddings __a : Dict = type_vocab_size __a : Any = type_sequence_label_size __a : Dict = initializer_range __a : Optional[Any] = num_labels __a : Optional[Any] = num_choices __a : Union[str, Any] = relative_attention __a : List[str] = position_biased_input __a : List[Any] = pos_att_type __a : Tuple = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Any = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[int] = None __a : int = None __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __a : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a )[0] __a : str = model(__a , token_type_ids=__a )[0] __a : Optional[int] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : int = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : List[Any] = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __a : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : str = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __a : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) A_ = True A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = DebertaVaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __a : Optional[Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : int = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __a : str = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
294
0
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __UpperCamelCase ( lowerCamelCase__ ): A_ = ["""image_processor""", """tokenizer"""] A_ = """LayoutLMv3ImageProcessor""" A_ = ("""LayoutLMv3Tokenizer""", """LayoutLMv3TokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): '''simple docstring''' __a : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , snake_case__ , ) __a : int = kwargs.pop('feature_extractor' ) __a : Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(snake_case__ , snake_case__ ) def __call__( self , __a , __a = None , __a = None , __a = None , __a = None , __a = True , __a = False , __a = None , __a = None , __a = 0 , __a = None , __a = None , __a = None , __a = False , __a = False , __a = False , __a = False , __a = True , __a = None , **__a , ): '''simple docstring''' if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' ) # first, apply the image processor __a : Optional[int] = self.image_processor(images=snake_case__ , return_tensors=snake_case__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(snake_case__ , snake_case__ ): __a : int = [text] # add batch dimension (as the image processor always adds a batch dimension) __a : List[Any] = features['''words'''] __a : Any = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=snake_case__ , add_special_tokens=snake_case__ , padding=snake_case__ , truncation=snake_case__ , max_length=snake_case__ , stride=snake_case__ , pad_to_multiple_of=snake_case__ , return_token_type_ids=snake_case__ , return_attention_mask=snake_case__ , return_overflowing_tokens=snake_case__ , return_special_tokens_mask=snake_case__ , return_offsets_mapping=snake_case__ , return_length=snake_case__ , verbose=snake_case__ , return_tensors=snake_case__ , **snake_case__ , ) # add pixel values __a : str = features.pop('pixel_values' ) if return_overflowing_tokens is True: __a : Dict = self.get_overflowing_images(snake_case__ , encoded_inputs['overflow_to_sample_mapping'] ) __a : int = images return encoded_inputs def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : Any = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(snake_case__ ) != len(snake_case__ ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' f""" {len(snake_case__ )} and {len(snake_case__ )}""" ) return images_with_overflow def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case__ , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case__ , ) return self.image_processor
362
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if is_torch_version('<' , '2.0.0' ) or not hasattr(_SCREAMING_SNAKE_CASE , '_dynamo' ): return False return isinstance(_SCREAMING_SNAKE_CASE , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : bool = True ): __a : int = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a : Any = is_compiled_module(_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[Any] = model __a : Union[str, Any] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = model.module if not keep_fpaa_wrapper: __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'forward' ) __a : str = model.__dict__.pop('_original_forward' , _SCREAMING_SNAKE_CASE ) if original_forward is not None: while hasattr(_SCREAMING_SNAKE_CASE , '__wrapped__' ): __a : Any = forward.__wrapped__ if forward == original_forward: break __a : str = forward if getattr(_SCREAMING_SNAKE_CASE , '_converted_to_transformer_engine' , _SCREAMING_SNAKE_CASE ): convert_model(_SCREAMING_SNAKE_CASE , to_transformer_engine=_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[str] = model __a : Optional[int] = compiled_model return model def lowerCamelCase (): PartialState().wait_for_everyone() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif PartialState().local_process_index == 0: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @contextmanager def lowerCamelCase (**_SCREAMING_SNAKE_CASE : Tuple ): for key, value in kwargs.items(): __a : Optional[int] = str(_SCREAMING_SNAKE_CASE ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ) and not hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , '__class__' , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ): return obj.__qualname__ if hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): return obj.__name__ return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): for key, value in source.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : int = destination.setdefault(_SCREAMING_SNAKE_CASE , {} ) merge_dicts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a : Tuple = value return destination def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = None ): if port is None: __a : List[str] = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
294
0
'''simple docstring''' from __future__ import annotations __lowercase : Optional[Any] = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : list[list[int]] , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[list[int]] , ): __a : Dict = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_lowercase ) ) ] # the reference grid __a : Any = 1 __a : List[Any] = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_lowercase ) ) ] # the action grid __a : str = init[0] __a : Any = init[1] __a : List[str] = 0 __a : int = g + heuristic[x][y] # cost from starting cell to destination cell __a : Dict = [[f, g, x, y]] __a : List[Any] = False # flag that is set when search is complete __a : Optional[int] = False # flag set if we can't find expand while not found and not resign: if len(_lowercase ) == 0: raise ValueError('Algorithm is unable to find solution' ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() __a : Optional[int] = cell.pop() __a : Dict = next_cell[2] __a : int = next_cell[3] __a : Union[str, Any] = next_cell[1] if x == goal[0] and y == goal[1]: __a : List[Any] = True else: for i in range(len(_lowercase ) ): # to try out different valid actions __a : Optional[Any] = x + DIRECTIONS[i][0] __a : List[Any] = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(_lowercase ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: __a : Dict = g + cost __a : List[Any] = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) __a : Any = 1 __a : Union[str, Any] = i __a : Tuple = [] __a : Tuple = goal[0] __a : Optional[Any] = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: __a : Dict = x - DIRECTIONS[action[x][y]][0] __a : Union[str, Any] = y - DIRECTIONS[action[x][y]][1] __a : Optional[int] = xa __a : Tuple = ya invpath.append([x, y] ) __a : Optional[int] = [] for i in range(len(_lowercase ) ): path.append(invpath[len(_lowercase ) - 1 - i] ) return path, action if __name__ == "__main__": __lowercase : str = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] __lowercase : int = [0, 0] # all coordinates are given in format [y,x] __lowercase : Dict = [len(grid) - 1, len(grid[0]) - 1] __lowercase : int = 1 # the cost map which pushes the path closer to the goal __lowercase : Optional[int] = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): __lowercase : Optional[Any] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map __lowercase : Optional[Any] = 99 __lowercase : Optional[int] = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
0
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : bool , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : float ): if depth < 0: raise ValueError('Depth cannot be less than 0' ) if not scores: raise ValueError('Scores cannot be empty' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) ) def lowerCamelCase (): __a : Tuple = [90, 23, 6, 33, 21, 65, 123, 34_423] __a : List[Any] = math.log(len(_SCREAMING_SNAKE_CASE ) , 2 ) print(F"""Optimal value : {minimax(0 , 0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
364
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class __UpperCamelCase : A_ = 42 A_ = None A_ = None def lowerCamelCase (_SCREAMING_SNAKE_CASE : TreeNode | None ): # Validation def is_valid_tree(_SCREAMING_SNAKE_CASE : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_SCREAMING_SNAKE_CASE ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( _SCREAMING_SNAKE_CASE : TreeNode | None , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _SCREAMING_SNAKE_CASE , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _SCREAMING_SNAKE_CASE ) ) return is_binary_search_tree_recursive_check(_SCREAMING_SNAKE_CASE , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __lowercase : str = logging.get_logger(__name__) class __UpperCamelCase ( __lowerCAmelCase ): A_ = ['''pixel_values'''] def __init__( self , __a = True , __a = None , __a = PILImageResampling.BICUBIC , __a = True , __a = True , __a = 1 / 255 , __a = None , __a = True , __a = None , __a = None , **__a , ): '''simple docstring''' super().__init__(**lowerCAmelCase_ ) __a : Any = size if size is not None else {'height': 224, 'width': 224} __a : Union[str, Any] = get_size_dict(lowerCAmelCase_ ) __a : Any = crop_size if crop_size is not None else {'height': 224, 'width': 224} __a : Dict = get_size_dict(lowerCAmelCase_ , default_to_square=lowerCAmelCase_ , param_name='crop_size' ) __a : Optional[int] = do_resize __a : List[Any] = do_rescale __a : Union[str, Any] = do_normalize __a : Any = do_center_crop __a : Optional[Any] = crop_size __a : List[str] = size __a : List[Any] = resample __a : List[Any] = rescale_factor __a : Optional[Any] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a : Tuple = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __UpperCAmelCase ( self , __a , __a , __a = PILImageResampling.BILINEAR , __a = None , **__a , ): '''simple docstring''' __a : Optional[int] = get_size_dict(lowerCAmelCase_ ) if "shortest_edge" in size: __a : Any = get_resize_output_image_size(lowerCAmelCase_ , size=size['shortest_edge'] , default_to_square=lowerCAmelCase_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a : str = (size['height'], size['width']) else: raise ValueError(f"""Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}""" ) return resize(lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def __UpperCAmelCase ( self , __a , __a , __a = None , **__a , ): '''simple docstring''' __a : List[str] = get_size_dict(lowerCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(lowerCAmelCase_ , size=(size['height'], size['width']) , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def __UpperCAmelCase ( self , __a , __a , __a = None , **__a ): '''simple docstring''' return rescale(lowerCAmelCase_ , scale=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def __UpperCAmelCase ( self , __a , __a , __a , __a = None , **__a , ): '''simple docstring''' return normalize(lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def __UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ): '''simple docstring''' __a : Optional[Any] = do_resize if do_resize is not None else self.do_resize __a : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __a : Tuple = do_normalize if do_normalize is not None else self.do_normalize __a : Any = do_center_crop if do_center_crop is not None else self.do_center_crop __a : List[str] = crop_size if crop_size is not None else self.crop_size __a : int = get_size_dict(lowerCAmelCase_ , param_name='crop_size' , default_to_square=lowerCAmelCase_ ) __a : Any = resample if resample is not None else self.resample __a : str = rescale_factor if rescale_factor is not None else self.rescale_factor __a : Dict = image_mean if image_mean is not None else self.image_mean __a : Dict = image_std if image_std is not None else self.image_std __a : Optional[Any] = size if size is not None else self.size __a : List[Any] = get_size_dict(lowerCAmelCase_ ) if not is_batched(lowerCAmelCase_ ): __a : Tuple = [images] if not valid_images(lowerCAmelCase_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. __a : str = [to_numpy_array(lowerCAmelCase_ ) for image in images] if do_resize: __a : int = [self.resize(image=lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ ) for image in images] if do_center_crop: __a : Optional[Any] = [self.center_crop(image=lowerCAmelCase_ , size=lowerCAmelCase_ ) for image in images] if do_rescale: __a : List[str] = [self.rescale(image=lowerCAmelCase_ , scale=lowerCAmelCase_ ) for image in images] if do_normalize: __a : Optional[Any] = [self.normalize(image=lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ ) for image in images] __a : Tuple = [to_channel_dimension_format(lowerCAmelCase_ , lowerCAmelCase_ ) for image in images] __a : Optional[Any] = {'pixel_values': images} return BatchFeature(data=lowerCAmelCase_ , tensor_type=lowerCAmelCase_ )
365
'''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. __lowercase : Dict = 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 (_SCREAMING_SNAKE_CASE : Optional[Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): from transformers.testing_utils import pytest_terminal_summary_main __a : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE , id=_SCREAMING_SNAKE_CASE )
294
0
'''simple docstring''' __lowercase : Tuple = 'Input must be a string of 8 numbers plus letter' __lowercase : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a : List[Any] = F"""Expected string as input, found {type(lowerCAmelCase__ ).__name__}""" raise TypeError(lowerCAmelCase__ ) __a : List[str] = spanish_id.replace('-' , '' ).upper() if len(lowerCAmelCase__ ) != 9: raise ValueError(lowerCAmelCase__ ) try: __a : Union[str, Any] = int(spanish_id_clean[0:8] ) __a : int = spanish_id_clean[8] except ValueError as ex: raise ValueError(lowerCAmelCase__ ) from ex if letter.isdigit(): raise ValueError(lowerCAmelCase__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
366
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): re.sub('<n>' , '' , _SCREAMING_SNAKE_CASE ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_SCREAMING_SNAKE_CASE ) )
294
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __UpperCamelCase : A_ = XGLMConfig A_ = {} A_ = "gelu" def __init__( self , __a , __a=14 , __a=7 , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=0.02 , ): '''simple docstring''' __a : Union[str, Any] = parent __a : Dict = batch_size __a : int = seq_length __a : str = is_training __a : List[str] = use_input_mask __a : Dict = use_labels __a : str = vocab_size __a : Tuple = d_model __a : Union[str, Any] = num_hidden_layers __a : str = num_attention_heads __a : int = ffn_dim __a : Optional[int] = activation_function __a : Optional[Any] = activation_dropout __a : Dict = attention_dropout __a : str = max_position_embeddings __a : Tuple = initializer_range __a : int = None __a : List[Any] = 0 __a : int = 2 __a : Dict = 1 def __UpperCAmelCase ( self ): '''simple docstring''' return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) __a : List[Any] = None if self.use_input_mask: __a : str = random_attention_mask([self.batch_size, self.seq_length] ) __a : Dict = self.get_config() __a : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def __UpperCAmelCase ( self ): '''simple docstring''' return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=UpperCamelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=UpperCamelCase__ , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.prepare_config_and_inputs() ( __a ) : Union[str, Any] = config_and_inputs __a : List[Any] = { '''input_ids''': input_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): A_ = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () A_ = (TFXGLMForCausalLM,) if is_tf_available() else () A_ = ( {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {} ) A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = TFXGLMModelTester(self ) __a : List[Any] = ConfigTester(self , config_class=UpperCamelCase__ , n_embd=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFXGLMModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def __UpperCAmelCase ( self ): '''simple docstring''' super().test_resize_token_embeddings() @require_tf class __UpperCamelCase ( unittest.TestCase ): @slow def __UpperCAmelCase ( self , __a=True ): '''simple docstring''' __a : Dict = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __a : List[Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __a : List[Any] = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on __a : int = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase__ ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __a : Dict = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) __a : List[Any] = tokenizer('Today is a nice day and' , return_tensors='tf' ) __a : Union[str, Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): __a : Optional[int] = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ , seed=[7, 0] ) __a : Any = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCamelCase__ ) __a : Tuple = ( '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due''' ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __a : List[Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __a : List[Any] = '''left''' # use different length sentences to test batching __a : int = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When''', '''Hello, my dog is a little''', ] __a : Dict = tokenizer(UpperCamelCase__ , return_tensors='tf' , padding=UpperCamelCase__ ) __a : str = inputs['''input_ids'''] __a : Union[str, Any] = model.generate(input_ids=UpperCamelCase__ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) __a : Tuple = tokenizer(sentences[0] , return_tensors='tf' ).input_ids __a : List[Any] = model.generate(input_ids=UpperCamelCase__ , max_new_tokens=12 ) __a : Union[str, Any] = tokenizer(sentences[1] , return_tensors='tf' ).input_ids __a : Dict = model.generate(input_ids=UpperCamelCase__ , max_new_tokens=12 ) __a : Optional[int] = tokenizer.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) __a : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCamelCase__ ) __a : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCamelCase__ ) __a : Union[str, Any] = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ''' '''a single''', '''Hello, my dog is a little bit of a shy one, but he is very friendly''', ] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , [non_padded_sentence, padded_sentence] )
367
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowercase : Any = [0, 25, 50] __lowercase : int = [25, 50, 75] __lowercase : List[str] = fuzz.membership.trimf(X, abca) __lowercase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowercase : List[Any] = np.ones(75) __lowercase : Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowercase : str = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowercase : List[Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowercase : Optional[Any] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowercase : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowercase : Optional[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowercase : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
294
0
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __lowercase : Optional[int] = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class __UpperCamelCase ( _a , unittest.TestCase ): A_ = DebertaVaTokenizer A_ = DebertaVaTokenizerFast A_ = True A_ = True def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __a : List[str] = DebertaVaTokenizer(__a , unk_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = 'this is a test' __a : int = 'this is a test' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = '<pad>' __a : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '[PAD]' ) self.assertEqual(len(__a ) , 3_0001 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 3_0000 ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ' \tHeLLo!how \n Are yoU? ' __a : str = ['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on __a : Union[str, Any] = DebertaVaTokenizer(__a , do_lower_case=__a ) __a : Any = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : Dict = DebertaVaTokenizerFast(__a , do_lower_case=__a ) __a : Optional[int] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = 'I was born in 92000, and this is falsé.' __a : Optional[int] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __a : List[Any] = DebertaVaTokenizer(__a , split_by_punct=__a ) __a : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : Optional[int] = DebertaVaTokenizerFast(__a , split_by_punct=__a ) __a : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = 'I was born in 92000, and this is falsé.' __a : Any = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __a : Optional[int] = DebertaVaTokenizer(__a , do_lower_case=__a , split_by_punct=__a ) __a : List[str] = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : List[str] = DebertaVaTokenizerFast(__a , do_lower_case=__a , split_by_punct=__a ) __a : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = 'I was born in 92000, and this is falsé.' __a : List[Any] = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __a : str = DebertaVaTokenizer(__a , do_lower_case=__a , split_by_punct=__a ) __a : List[str] = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : Dict = DebertaVaTokenizerFast(__a , do_lower_case=__a , split_by_punct=__a ) __a : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = 'I was born in 92000, and this is falsé.' __a : Optional[Any] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __a : str = DebertaVaTokenizer(__a , do_lower_case=__a , split_by_punct=__a ) __a : str = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : Tuple = DebertaVaTokenizerFast(__a , do_lower_case=__a , split_by_punct=__a ) __a : str = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ' \tHeLLo!how \n Are yoU? ' __a : int = ['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on __a : Union[str, Any] = DebertaVaTokenizer(__a , do_lower_case=__a , split_by_punct=__a ) __a : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : List[Any] = DebertaVaTokenizerFast(__a , do_lower_case=__a , split_by_punct=__a ) __a : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.get_tokenizer() __a : List[Any] = self.get_rust_tokenizer() __a : List[str] = 'I was born in 92000, and this is falsé.' __a : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(__a , add_special_tokens=__a ) ) __a : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(__a , add_special_tokens=__a ) ) self.assertListEqual(__a , __a ) __a : Union[str, Any] = tokenizer.encode(__a , add_special_tokens=__a ) __a : Dict = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : Optional[Any] = self.get_rust_tokenizer() __a : List[str] = tokenizer.encode(__a ) __a : Tuple = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'This is a test' __a : Tuple = [13, 1, 4398, 25, 21, 1289] __a : List[Any] = ['▁', 'T', 'his', '▁is', '▁a', '▁test'] __a : Union[str, Any] = ['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] __a : Dict = DebertaVaTokenizer(__a , keep_accents=__a ) __a : Optional[int] = DebertaVaTokenizerFast(__a , keep_accents=__a ) __a : Union[str, Any] = tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : int = tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Dict = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual(__a , __a ) __a : List[str] = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : List[str] = rust_tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual(__a , __a ) # fmt: off __a : Any = 'I was born in 92000, and this is falsé.' __a : int = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] __a : Tuple = ['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] __a : Dict = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __a : Tuple = tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : int = tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Optional[Any] = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual(__a , __a ) __a : List[str] = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : int = rust_tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaTokenizer(__a ) __a : Any = tokenizer.encode('sequence builders' ) __a : Optional[Any] = tokenizer.encode('multi-sequence build' ) __a : Dict = tokenizer.build_inputs_with_special_tokens(__a ) __a : List[str] = tokenizer.build_inputs_with_special_tokens(__a , __a ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , __a ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , __a , ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = {'input_ids': [[1, 3_9867, 36, 1_9390, 486, 27, 3_5052, 8_1436, 18, 6_0685, 1225, 7, 3_5052, 8_1436, 18, 9367, 1_6899, 18, 1_5937, 53, 594, 773, 18, 1_6287, 3_0465, 36, 1_5937, 6, 4_1139, 38, 3_6979, 6_0763, 191, 6, 3_4132, 99, 6, 5_0538, 390, 4_3230, 6, 3_4132, 2779, 2_0850, 14, 699, 1072, 1194, 36, 382, 1_0901, 53, 7, 699, 1072, 2084, 36, 2_0422, 630, 53, 19, 105, 3049, 1896, 1053, 1_6899, 1506, 11, 3_7978, 4243, 7, 1237, 3_1869, 200, 1_6566, 654, 6, 3_5052, 8_1436, 7, 5_5630, 1_3593, 4, 2], [1, 26, 1_5011, 13, 667, 8, 1053, 18, 2_3611, 1237, 7_2356, 1_2820, 34, 10_4134, 1209, 35, 1_3313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 1_5785, 1_4951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name='microsoft/deberta-v2-xlarge' , revision='ad6e42c1532ddf3a15c39246b63f5559d558b670' , )
368
'''simple docstring''' import sys __lowercase : Union[str, Any] = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : List[str] = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = N ): __a : Optional[int] = -sys.maxsize - 1 __a : Optional[Any] = n[:13] __a : int = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): __a : List[Any] = substr[1:] + n[cur_index] cur_index += 1 else: __a : Dict = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) __a : Optional[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
294
0
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCamelCase (_SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : set , _SCREAMING_SNAKE_CASE : set , _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : PriorityQueue , _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : float | int , ): for nxt, d in graph[v]: if nxt in visited_forward: continue __a : str = cst_fwd.get(__UpperCamelCase , np.inf ) __a : Optional[int] = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __a : str = new_cost_f __a : Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __a : List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : dict ): __a : List[str] = -1 __a : Any = set() __a : List[str] = set() __a : Tuple = {source: 0} __a : Optional[Any] = {destination: 0} __a : int = {source: None} __a : Optional[int] = {destination: None} __a : Union[str, Any] = PriorityQueue() __a : Any = PriorityQueue() __a : Any = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __a , __a : str = queue_forward.get() visited_forward.add(__UpperCamelCase ) __a , __a : Dict = queue_backward.get() visited_backward.add(__UpperCamelCase ) __a : Optional[int] = pass_and_relaxation( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) __a : int = pass_and_relaxation( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __a : Tuple = shortest_distance return shortest_path_distance __lowercase : Optional[int] = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } __lowercase : Union[str, Any] = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
369
'''simple docstring''' import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = CodeGenTokenizer A_ = CodeGenTokenizerFast A_ = True A_ = {"add_prefix_space": True} A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __a : Tuple = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __a : Union[str, Any] = dict(zip(__a , range(len(__a ) ) ) ) __a : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : Dict = {'unk_token': '<unk>'} __a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__a ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = 'lower newer' __a : Tuple = 'lower newer' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __a : str = 'lower newer' __a : Tuple = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) self.assertListEqual(__a , __a ) __a : List[str] = tokens + [tokenizer.unk_token] __a : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Any = 'lower newer' # Testing tokenization __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) __a : Dict = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids without special tokens __a : int = tokenizer.encode(__a , add_special_tokens=__a , add_prefix_space=__a ) __a : Tuple = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids with special tokens __a : Tuple = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Union[str, Any] = tokenizer.encode(__a , add_prefix_space=__a ) __a : int = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # Testing the unknown token __a : Any = tokens + [rust_tokenizer.unk_token] __a : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' pass def __UpperCAmelCase ( self , __a=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : Optional[int] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) # Simple input __a : List[Any] = 'This is a simple input' __a : Tuple = ['This is a simple input 1', 'This is a simple input 2'] __a : Tuple = ('This is a simple input', 'This is a pair') __a : str = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) # Pair input self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __a : str = 'This is a simple input' __a : Any = ['This is a simple input looooooooong', 'This is a simple input'] __a : Optional[int] = ('This is a simple input', 'This is a pair') __a : Optional[Any] = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __a : int = tokenizer.pad_token_id __a : List[Any] = tokenizer(__a , padding='max_length' , max_length=30 , return_tensors='np' ) __a : Union[str, Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) __a : Optional[Any] = tokenizer(*__a , padding='max_length' , max_length=60 , return_tensors='np' ) __a : List[Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = '$$$' __a : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__a , add_bos_token=__a ) __a : Union[str, Any] = 'This is a simple input' __a : List[Any] = ['This is a simple input 1', 'This is a simple input 2'] __a : List[Any] = tokenizer.bos_token_id __a : List[str] = tokenizer(__a ) __a : Optional[Any] = tokenizer(__a ) self.assertEqual(out_s.input_ids[0] , __a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __a : Any = tokenizer.decode(out_s.input_ids ) __a : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' ) __a : Optional[int] = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' __a : Tuple = '\nif len_a > len_b: result = a\nelse: result = b' __a : Optional[int] = tokenizer.encode(__a ) __a : Union[str, Any] = ['^#', re.escape('<|endoftext|>' ), '^\'\'\'', '^"""', '\n\n\n'] __a : Tuple = tokenizer.decode(__a , truncate_before_pattern=__a ) self.assertEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' pass
294
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : List[Any] = { 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'configuration_data2vec_text': [ 'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecTextConfig', 'Data2VecTextOnnxConfig', ], 'configuration_data2vec_vision': [ 'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecVisionConfig', 'Data2VecVisionOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[Any] = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] __lowercase : str = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] __lowercase : Union[str, Any] = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): __lowercase : str = [ 'TFData2VecVisionForImageClassification', 'TFData2VecVisionForSemanticSegmentation', 'TFData2VecVisionModel', 'TFData2VecVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __lowercase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError('iterations must be defined as integers' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) __a : Dict = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_SCREAMING_SNAKE_CASE ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowercase : str = 16 __lowercase : int = 32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 ): __a : Optional[Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) __a : Dict = load_dataset('glue' , 'mrpc' ) def tokenize_function(_SCREAMING_SNAKE_CASE : Any ): # max_length=None => use the model max length (it's actually the default) __a : str = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=a__ , max_length=a__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __a : Any = datasets.map( a__ , batched=a__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a : List[str] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. __a : List[str] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __a : Tuple = 16 elif accelerator.mixed_precision != "no": __a : Union[str, Any] = 8 else: __a : List[Any] = None return tokenizer.pad( a__ , padding='longest' , max_length=a__ , pad_to_multiple_of=a__ , return_tensors='pt' , ) # Instantiate dataloaders. __a : Optional[Any] = DataLoader( tokenized_datasets['train'] , shuffle=a__ , collate_fn=a__ , batch_size=a__ ) __a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=a__ , collate_fn=a__ , batch_size=a__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __lowercase : List[str] = mocked_dataloaders # noqa: F811 def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): if os.environ.get('TESTING_MOCKED_DATALOADERS' , a__ ) == "1": __a : Tuple = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __a : Union[str, Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: __a : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a : List[str] = config['lr'] __a : str = int(config['num_epochs'] ) __a : List[str] = int(config['seed'] ) __a : str = int(config['batch_size'] ) set_seed(a__ ) __a , __a : Union[str, Any] = get_dataloaders(a__ , a__ ) __a : Optional[Any] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation __a : Union[str, Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __a : Any = batch_size // MAX_GPU_BATCH_SIZE __a : Optional[Any] = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a : Dict = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=a__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __a : Any = model.to(accelerator.device ) # Instantiate optimizer __a : Tuple = AdamW(params=model.parameters() , lr=a__ ) # Instantiate scheduler __a : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=a__ , num_warmup_steps=100 , num_training_steps=(len(a__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a : Tuple = accelerator.prepare( a__ , a__ , a__ , a__ , a__ ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __a : List[Any] = os.path.split(a__ )[-1].split('.' )[0] accelerator.init_trackers(a__ , a__ ) # Now we train the model for epoch in range(a__ ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __a : Optional[Any] = 0 for step, batch in enumerate(a__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __a : List[Any] = model(**a__ ) __a : int = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __a : str = loss / gradient_accumulation_steps accelerator.backward(a__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(a__ ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __a : Optional[int] = model(**a__ ) __a : Optional[Any] = outputs.logits.argmax(dim=-1 ) __a , __a : str = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=a__ , references=a__ , ) __a : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , a__ ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { 'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(a__ ), 'epoch': epoch, } , step=a__ , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowerCamelCase (): __a : Tuple = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=a__ , default=a__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=a__ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) __a : Tuple = parser.parse_args() __a : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(a__ , a__ ) if __name__ == "__main__": main()
371
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , ): '''simple docstring''' __a : List[Any] = size if size is not None else {'height': 18, 'width': 18} __a : int = parent __a : Dict = batch_size __a : Optional[int] = num_channels __a : List[Any] = image_size __a : Tuple = min_resolution __a : str = max_resolution __a : str = do_resize __a : Optional[Any] = size __a : str = apply_ocr def __UpperCAmelCase ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LayoutLMvaImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'apply_ocr' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __a : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched __a : Any = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : Tuple = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __a : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : List[str] = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __a : str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) __a : Tuple = Image.open(ds[0]['file'] ).convert('RGB' ) __a : Optional[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a : Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 __a : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False __a : List[Any] = LayoutLMvaImageProcessor(apply_ocr=__a ) __a : List[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
294
0
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( snake_case_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , 'tf_padding' ) ) self.parent.assertTrue(hasattr(_A , 'depth_multiplier' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=3 , __a=32 , __a=0.25 , __a=8 , __a=True , __a=1024 , __a=32 , __a="relu6" , __a=0.1 , __a=0.02 , __a=True , __a=True , __a=10 , __a=None , ): '''simple docstring''' __a : Optional[int] = parent __a : List[str] = batch_size __a : Optional[int] = num_channels __a : int = image_size __a : Optional[Any] = depth_multiplier __a : str = min_depth __a : Any = tf_padding __a : str = int(last_hidden_size * depth_multiplier ) __a : List[Any] = output_stride __a : Optional[int] = hidden_act __a : str = classifier_dropout_prob __a : Any = use_labels __a : Optional[Any] = is_training __a : Tuple = num_labels __a : Tuple = initializer_range __a : Optional[int] = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Union[str, Any] = None __a : int = None if self.use_labels: __a : Tuple = ids_tensor([self.batch_size] , self.num_labels ) __a : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a : List[str] = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a , __a ): '''simple docstring''' __a : Any = MobileNetVaModel(config=_A ) model.to(_A ) model.eval() __a : List[Any] = model(_A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __UpperCAmelCase ( self , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : str = MobileNetVaForImageClassification(_A ) model.to(_A ) model.eval() __a : Union[str, Any] = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.prepare_config_and_inputs() __a : Dict = config_and_inputs __a : List[str] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): A_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () A_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = MobileNetVaModelTester(self ) __a : Tuple = MobileNetVaConfigTester(self , config_class=_A , has_text_modality=_A ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV1 does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV1 does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV1 does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_A ) __a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : int = [*signature.parameters.keys()] __a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : Dict = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __a : Optional[Any] = model(**self._prepare_for_class(_A , _A ) ) __a : str = outputs.hidden_states __a : Dict = 26 self.assertEqual(len(_A ) , _A ) __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Union[str, Any] = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[int] = True check_hidden_states_output(_A , _A , _A ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Tuple = MobileNetVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def lowerCamelCase (): __a : str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224' ).to(_A ) __a : int = self.default_image_processor __a : List[Any] = prepare_img() __a : List[Any] = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __a : int = model(**_A ) # verify the logits __a : Dict = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _A ) __a : Tuple = torch.tensor([-4.1739, -1.1233, 3.1205] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) )
350
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
0
'''simple docstring''' from typing import Any class __UpperCamelCase : def __init__( self , __a ): '''simple docstring''' __a : List[Any] = data __a : Dict = None def __repr__( self ): '''simple docstring''' return f"""Node({self.data})""" class __UpperCamelCase : def __init__( self ): '''simple docstring''' __a : Optional[Any] = None def __iter__( self ): '''simple docstring''' __a : Optional[Any] = self.head while node: yield node.data __a : Any = node.next def __len__( self ): '''simple docstring''' return sum(1 for _ in self ) def __repr__( self ): '''simple docstring''' return "->".join([str(__a ) for item in self] ) def __getitem__( self , __a ): '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , __a , __a ): '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) __a : int = self.head for _ in range(__a ): __a : List[str] = current.next __a : int = data def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.insert_nth(len(self ) , __a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.insert_nth(0 , __a ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) __a : Optional[int] = Node(__a ) if self.head is None: __a : Union[str, Any] = new_node elif index == 0: __a : List[Any] = self.head # link new_node to head __a : int = new_node else: __a : List[Any] = self.head for _ in range(index - 1 ): __a : Optional[Any] = temp.next __a : str = temp.next __a : Tuple = new_node def __UpperCAmelCase ( self ): # print every node data '''simple docstring''' print(self ) def __UpperCAmelCase ( self ): '''simple docstring''' return self.delete_nth(0 ) def __UpperCAmelCase ( self ): # delete from tail '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def __UpperCAmelCase ( self , __a = 0 ): '''simple docstring''' if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) __a : List[Any] = self.head # default first node if index == 0: __a : Optional[int] = self.head.next else: __a : int = self.head for _ in range(index - 1 ): __a : int = temp.next __a : Union[str, Any] = temp.next __a : int = temp.next.next return delete_node.data def __UpperCAmelCase ( self ): '''simple docstring''' return self.head is None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = None __a : Optional[Any] = self.head while current: # Store the current node's next node. __a : List[Any] = current.next # Make the current node's next point backwards __a : Optional[int] = prev # Make the previous node be the current node __a : List[str] = current # Make the current node the next node (to progress iteration) __a : Tuple = next_node # Return prev in order to put the head at the end __a : List[Any] = prev def lowerCamelCase (): __a : int = LinkedList() assert linked_list.is_empty() is True assert str(A__ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(A__ ) == i linked_list.insert_nth(A__ , i + 1 ) assert str(A__ ) == "->".join(str(A__ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(A__ ) == "->".join(str(A__ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(A__ ) == 9 assert str(A__ ) == "->".join(str(A__ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): __a : List[Any] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(A__ ) == "->".join(str(A__ ) for i in range(-8 , 1 ) ) def lowerCamelCase (): __a : Tuple = [ -9, 100, Node(77_345_112 ), """dlrow olleH""", 7, 5_555, 0, -1_9_2.5_5_5_5_5, """Hello, world!""", 7_7.9, Node(10 ), None, None, 1_2.2_0, ] __a : Tuple = LinkedList() for i in test_input: linked_list.insert_tail(A__ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(A__ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head __a : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(A__ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail __a : List[Any] = linked_list.delete_tail() assert result == 1_2.2 assert ( str(A__ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list __a : List[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(A__ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(A__ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(A__ ) assert ( str(A__ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(A__ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase (): from doctest import testmod testmod() __a : str = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(A__ ) print('\nReading/changing Node data using indexing:' ) print(F"""Element at Position 1: {linked_list[1]}""" ) __a : Tuple = input('Enter New Value: ' ).strip() print('New list:' ) print(A__ ) print(F"""length of linked_list is : {len(A__ )}""" ) if __name__ == "__main__": main()
351
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a ): '''simple docstring''' super().__init__() __a : int = module __a : List[Any] = nn.Sequential( nn.Linear(module.in_features , __a , bias=__a ) , nn.Linear(__a , module.out_features , bias=__a ) , ) __a : int = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=__a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' return self.module(__a , *__a , **__a ) + self.adapter(__a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module A_ = "bigscience/bloom-1b7" # Constant values A_ = 2.109659552692574 A_ = "Hello my name is" A_ = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) A_ = 10 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = AutoTokenizer.from_pretrained(self.model_name ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Models and tokenizer __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_abit.config self.assertTrue(hasattr(__a , 'quantization_config' ) ) __a : Union[str, Any] = config.to_dict() __a : Tuple = config.to_diff_dict() __a : Tuple = config.to_json_string() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit __a : List[Any] = self.model_fpaa.get_memory_footprint() __a : List[Any] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __a : Tuple = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(__a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Union[str, Any] = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BitsAndBytesConfig() __a : Tuple = True __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ) __a : List[Any] = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = BitsAndBytesConfig() with self.assertRaises(__a ): __a : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , load_in_abit=__a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(__a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(__a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __a : List[str] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Optional[int] = self.model_fpaa.to(torch.floataa ) __a : Tuple = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __a : List[Any] = self.model_fpaa.to('cpu' ) # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.half() # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.float() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=__a , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' __a : Any = 't5-small' __a : Tuple = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __a : int = AutoTokenizer.from_pretrained(cls.model_name ) __a : Union[str, Any] = 'Translate in German: Hello, my dog is cute' def __UpperCAmelCase ( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaForConditionalGeneration __a : Optional[int] = TaForConditionalGeneration._keep_in_fpaa_modules __a : List[str] = None # test with `t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[int] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : Any = model.generate(**__a ) # test with `flan-t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[Any] = model.generate(**__a ) __a : Optional[int] = modules def __UpperCAmelCase ( self ): '''simple docstring''' import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[str] = model.generate(**__a ) # test with `flan-t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : int = model.generate(**__a ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # model_name __a : List[Any] = 'bigscience/bloom-560m' __a : Union[str, Any] = 't5-small' # Different types of model __a : Optional[Any] = AutoModel.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Sequence classification model __a : Dict = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=__a , device_map='auto' ) # CausalLM model __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Seq2seq model __a : Any = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' del self.pipe gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __a : str = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=__a , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __a : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __a : str = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'facebook/opt-350m' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __a : Tuple = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __a : Tuple = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(__a ) ): __a : str = LoRALayer(module.q_proj , rank=16 ) __a : str = LoRALayer(module.k_proj , rank=16 ) __a : Optional[int] = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __a : List[str] = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __a : int = model.forward(**__a ) out.logits.norm().backward() for module in model.modules(): if isinstance(__a , __a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(__a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "gpt2-xl" A_ = 3.3191854854152187
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : list ): def merge(_SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(lowerCAmelCase__ ) <= 1: return collection __a : str = len(lowerCAmelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __lowercase : Optional[Any] = input('Enter numbers separated by a comma:\n').strip() __lowercase : Optional[int] = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',')
352
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAmelCase_ ): A_ = None A_ = None A_ = None A_ = None class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a=1 , __a=0 , __a=2 , __a=512 , __a="cls" , __a=False , __a=True , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Any = project_dim __a : Optional[Any] = pooler_fn __a : int = learn_encoder __a : str = use_attention_mask class __UpperCamelCase ( lowerCAmelCase_ ): A_ = [r"pooler", r"logit_scale"] A_ = [r"position_ids", r"predictions.decoder.bias"] A_ = "roberta" A_ = RobertaSeriesConfig def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Optional[Any] = XLMRobertaModel(__a ) __a : str = nn.Linear(config.hidden_size , config.project_dim ) __a : Optional[int] = getattr(__a , 'has_pre_transformation' , __a ) if self.has_pre_transformation: __a : int = nn.Linear(config.hidden_size , config.project_dim ) __a : List[str] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Tuple = self.base_model( input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , ) if self.has_pre_transformation: __a : Optional[Any] = outputs['hidden_states'][-2] __a : Optional[int] = self.pre_LN(__a ) __a : Union[str, Any] = self.transformation_pre(__a ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __a : Optional[Any] = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
294
0
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.5, 0.5, 0.5] , __a=[0.5, 0.5, 0.5] , __a=False , ): '''simple docstring''' __a : Optional[Any] = size if size is not None else {'height': 20, 'width': 20} __a : Union[str, Any] = crop_size if crop_size is not None else {'height': 18, 'width': 18} __a : Tuple = parent __a : Optional[int] = batch_size __a : List[str] = num_channels __a : Dict = image_size __a : Optional[Any] = min_resolution __a : Optional[Any] = max_resolution __a : Optional[Any] = do_resize __a : Any = size __a : Union[str, Any] = do_center_crop __a : str = crop_size __a : int = do_normalize __a : Any = image_mean __a : int = image_std __a : str = do_reduce_labels def __UpperCAmelCase ( self ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCamelCase (): __a : Dict = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __a : Dict = Image.open(dataset[0]['file'] ) __a : int = Image.open(dataset[1]['file'] ) return image, map def lowerCamelCase (): __a : Any = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __a : Union[str, Any] = Image.open(ds[0]['file'] ) __a : str = Image.open(ds[1]['file'] ) __a : List[str] = Image.open(ds[2]['file'] ) __a : Any = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = BeitImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BeitImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'do_center_crop' ) ) self.assertTrue(hasattr(__a , 'center_crop' ) ) self.assertTrue(hasattr(__a , 'do_normalize' ) ) self.assertTrue(hasattr(__a , 'image_mean' ) ) self.assertTrue(hasattr(__a , 'image_std' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 20, 'width': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) self.assertEqual(image_processor.do_reduce_labels , __a ) __a : Optional[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__a ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) self.assertEqual(image_processor.do_reduce_labels , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __a : Dict = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __a : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __a : Optional[int] = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __a : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __a : Any = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) __a : Tuple = [] for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __a : Any = image_processing(image_inputs[0] , maps[0] , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched __a : int = image_processing(__a , __a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test not batched input (PIL images) __a , __a : Union[str, Any] = prepare_semantic_single_inputs() __a : Any = image_processing(__a , __a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched input (PIL images) __a , __a : Tuple = prepare_semantic_batch_inputs() __a : Optional[int] = image_processing(__a , __a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __a , __a : Tuple = prepare_semantic_single_inputs() __a : List[str] = image_processing(__a , __a , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 150 ) __a : Union[str, Any] = True __a : Tuple = image_processing(__a , __a , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 )
353
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 1_000 ): __a : List[Any] = 3 __a : Optional[int] = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f'''{solution() = }''')
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __lowercase : str = logging.get_logger(__name__) # General docstring __lowercase : List[str] = 'MobileNetV1Config' # Base docstring __lowercase : Tuple = 'google/mobilenet_v1_1.0_224' __lowercase : List[Any] = [1, 10_24, 7, 7] # Image classification docstring __lowercase : int = 'google/mobilenet_v1_1.0_224' __lowercase : Any = 'tabby, tabby cat' __lowercase : Dict = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any]=None ): __a : Dict = {} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = model.mobilenet_va else: __a : List[Any] = model __a : Dict = 'MobilenetV1/Conv2d_0/' __a : Dict = backbone.conv_stem.convolution.weight __a : Optional[Any] = backbone.conv_stem.normalization.bias __a : int = backbone.conv_stem.normalization.weight __a : int = backbone.conv_stem.normalization.running_mean __a : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): __a : int = i + 1 __a : Dict = i * 2 __a : Dict = backbone.layer[pt_index] __a : Dict = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" __a : Union[str, Any] = pointer.convolution.weight __a : Optional[Any] = pointer.normalization.bias __a : Union[str, Any] = pointer.normalization.weight __a : List[Any] = pointer.normalization.running_mean __a : Tuple = pointer.normalization.running_var __a : List[str] = backbone.layer[pt_index + 1] __a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" __a : Optional[int] = pointer.convolution.weight __a : List[str] = pointer.normalization.bias __a : Dict = pointer.normalization.weight __a : Dict = pointer.normalization.running_mean __a : Optional[int] = pointer.normalization.running_var if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Any = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __a : Optional[int] = model.classifier.weight __a : List[Any] = model.classifier.bias return tf_to_pt_map def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __a : Union[str, Any] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) __a : List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = array # Build TF to PyTorch weights loading map __a : Optional[int] = _build_tf_to_pytorch_map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue __a : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __a : Optional[Any] = np.transpose(_SCREAMING_SNAKE_CASE , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __a : Union[str, Any] = array.squeeze().transpose() else: __a : Dict = np.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) __a : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) tf_weights.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp_1' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/ExponentialMovingAverage' , _SCREAMING_SNAKE_CASE ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def lowerCamelCase (_SCREAMING_SNAKE_CASE : torch.Tensor , _SCREAMING_SNAKE_CASE : nn.Convad ): __a , __a : Any = features.shape[-2:] __a , __a : int = conv_layer.stride __a , __a : Any = conv_layer.kernel_size if in_height % stride_height == 0: __a : int = max(kernel_height - stride_height , 0 ) else: __a : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __a : Any = max(kernel_width - stride_width , 0 ) else: __a : str = max(kernel_width - (in_width % stride_width) , 0 ) __a : int = pad_along_width // 2 __a : Dict = pad_along_width - pad_left __a : List[str] = pad_along_height // 2 __a : Union[str, Any] = pad_along_height - pad_top __a : str = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'constant' , 0.0 ) class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a , __a , __a , __a = 1 , __a = 1 , __a = False , __a = True , __a = True , ): '''simple docstring''' super().__init__() __a : Optional[int] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) __a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __a : Union[str, Any] = nn.Convad( in_channels=__a , out_channels=__a , kernel_size=__a , stride=__a , padding=__a , groups=__a , bias=__a , padding_mode='zeros' , ) if use_normalization: __a : List[str] = nn.BatchNormad( num_features=__a , eps=config.layer_norm_eps , momentum=0.9997 , affine=__a , track_running_stats=__a , ) else: __a : Tuple = None if use_activation: if isinstance(__a , __a ): __a : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , __a ): __a : Union[str, Any] = ACTaFN[config.hidden_act] else: __a : Dict = config.hidden_act else: __a : List[Any] = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.tf_padding: __a : Union[str, Any] = apply_tf_padding(__a , self.convolution ) __a : Union[str, Any] = self.convolution(__a ) if self.normalization is not None: __a : str = self.normalization(__a ) if self.activation is not None: __a : Optional[int] = self.activation(__a ) return features class __UpperCamelCase ( lowerCAmelCase_ ): A_ = MobileNetVaConfig A_ = load_tf_weights_in_mobilenet_va A_ = "mobilenet_v1" A_ = "pixel_values" A_ = False def __UpperCAmelCase ( self , __a ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __lowercase : Any = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowercase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a = True ): '''simple docstring''' super().__init__(__a ) __a : Optional[int] = config __a : str = 32 __a : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) __a : Union[str, Any] = MobileNetVaConvLayer( __a , in_channels=config.num_channels , out_channels=__a , kernel_size=3 , stride=2 , ) __a : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __a : Any = nn.ModuleList() for i in range(13 ): __a : Union[str, Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 __a : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=3 , stride=strides[i] , groups=__a , ) ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=1 , ) ) __a : Optional[int] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __UpperCAmelCase ( self , __a ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a : int = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __a : Union[str, Any] = self.conv_stem(__a ) __a : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __a : List[str] = layer_module(__a ) if output_hidden_states: __a : List[Any] = all_hidden_states + (hidden_states,) __a : str = hidden_states if self.pooler is not None: __a : Union[str, Any] = torch.flatten(self.pooler(__a ) , start_dim=1 ) else: __a : int = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__a , pooler_output=__a , hidden_states=__a , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Tuple = config.num_labels __a : Tuple = MobileNetVaModel(__a ) __a : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __a : Any = nn.Dropout(config.classifier_dropout_prob , inplace=__a ) __a : Any = nn.Linear(__a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Dict = self.mobilenet_va(__a , output_hidden_states=__a , return_dict=__a ) __a : List[str] = outputs.pooler_output if return_dict else outputs[1] __a : int = self.classifier(self.dropout(__a ) ) __a : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a : int = 'single_label_classification' else: __a : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __a : Optional[Any] = MSELoss() if self.num_labels == 1: __a : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __a : List[str] = CrossEntropyLoss() __a : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a : Tuple = BCEWithLogitsLoss() __a : Optional[int] = loss_fct(__a , __a ) if not return_dict: __a : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=__a , logits=__a , hidden_states=outputs.hidden_states , )
294
0
def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict = 1_000 ): __a : Dict = 2**power __a : int = str(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = list(_SCREAMING_SNAKE_CASE ) __a : List[Any] = 0 for i in list_num: sum_of_num += int(_SCREAMING_SNAKE_CASE ) return sum_of_num if __name__ == "__main__": __lowercase : Optional[int] = int(input('Enter the power of 2: ').strip()) print('2 ^ ', power, ' = ', 2**power) __lowercase : Optional[Any] = solution(power) print('Sum of the digits is: ', result)
355
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase : str = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "dhaka" , _SCREAMING_SNAKE_CASE : int = 5 ): __a : Optional[Any] = min(_SCREAMING_SNAKE_CASE , 50 ) # Prevent abuse! __a : Optional[Any] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } __a : Tuple = requests.get('https://www.google.com/search' , params=_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ) __a : Dict = BeautifulSoup(html.text , 'html.parser' ) __a : List[str] = ''.join( re.findall(r'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) __a : Optional[Any] = json.dumps(_SCREAMING_SNAKE_CASE ) __a : List[str] = json.loads(_SCREAMING_SNAKE_CASE ) __a : List[Any] = re.findall( r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , _SCREAMING_SNAKE_CASE , ) if not matched_google_image_data: return 0 __a : Tuple = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(_SCREAMING_SNAKE_CASE ) , ) __a : Optional[Any] = re.findall( r'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , _SCREAMING_SNAKE_CASE , ) for index, fixed_full_res_image in enumerate(_SCREAMING_SNAKE_CASE ): if index >= max_images: return index __a : List[str] = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Tuple = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Dict = urllib.request.build_opener() __a : Union[str, Any] = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(_SCREAMING_SNAKE_CASE ) __a : List[Any] = F"""query_{query.replace(" " , "_" )}""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): os.makedirs(_SCREAMING_SNAKE_CASE ) urllib.request.urlretrieve( # noqa: S310 _SCREAMING_SNAKE_CASE , F"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: __lowercase : Optional[int] = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print('Please provide a search term.') raise
294
0
'''simple docstring''' from __future__ import annotations def lowerCamelCase (_SCREAMING_SNAKE_CASE : list[int] ): __a : List[str] = len(lowerCamelCase_ ) // 2 # choose the middle 3 elements __a : Dict = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split(',' ) names.sort() __a : Union[str, Any] = 0 __a : Tuple = 0 for i, name in enumerate(_SCREAMING_SNAKE_CASE ): for letter in name: name_score += ord(_SCREAMING_SNAKE_CASE ) - 64 total_score += (i + 1) * name_score __a : Any = 0 return total_score if __name__ == "__main__": print(solution())
294
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a ): '''simple docstring''' __a : str = params __a : Union[str, Any] = np.array(_A ) __a : List[str] = np.array([len(_A ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , __a ): '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self ): '''simple docstring''' return len(self.lengths ) def __UpperCAmelCase ( self ): '''simple docstring''' assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.params.max_model_input_size __a : Union[str, Any] = self.lengths > max_len logger.info(f"""Splitting {sum(_A )} too long sequences.""" ) def divide_chunks(__a , __a ): return [l[i : i + n] for i in range(0 , len(_A ) , _A )] __a : Optional[int] = [] __a : int = [] if self.params.mlm: __a : int = self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'] else: __a : Optional[Any] = self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: __a : Optional[Any] = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __a : Optional[Any] = np.insert(_A , 0 , _A ) if sub_s[-1] != sep_id: __a : List[Any] = np.insert(_A , len(_A ) , _A ) assert len(_A ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(_A ) new_tok_ids.extend(_A ) new_lengths.extend([len(_A ) for l in sub_seqs] ) __a : Union[str, Any] = np.array(_A ) __a : Union[str, Any] = np.array(_A ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = len(self ) __a : Dict = self.lengths > 11 __a : Union[str, Any] = self.token_ids[indices] __a : str = self.lengths[indices] __a : Any = len(self ) logger.info(f"""Remove {init_size - new_size} too short (<=11 tokens) sequences.""" ) def __UpperCAmelCase ( self ): '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: __a : Optional[Any] = self.params.special_tok_ids['unk_token'] __a : Optional[Any] = len(self ) __a : Tuple = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __a : Any = (unk_occs / self.lengths) < 0.5 __a : Any = self.token_ids[indices] __a : str = self.lengths[indices] __a : Optional[Any] = len(self ) logger.info(f"""Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).""" ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.params.is_master: return logger.info(f"""{len(self )} sequences""" ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = [t[0] for t in batch] __a : Any = [t[1] for t in batch] assert len(_A ) == len(_A ) # Max for paddings __a : Any = max(_A ) # Pad token ids if self.params.mlm: __a : Optional[int] = self.params.special_tok_ids['pad_token'] else: __a : Tuple = self.params.special_tok_ids['unk_token'] __a : List[str] = [list(t.astype(_A ) ) + [pad_idx] * (max_seq_len_ - len(_A )) for t in token_ids] assert len(tk_ ) == len(_A ) assert all(len(_A ) == max_seq_len_ for t in tk_ ) __a : Tuple = torch.tensor(tk_ ) # (bs, max_seq_len_) __a : Any = torch.tensor(_A ) # (bs) return tk_t, lg_t
357
'''simple docstring''' __lowercase : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __lowercase : List[str] = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] ): __a : Any = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : Dict = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: __a : List[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __lowercase : Union[str, Any] = topological_sort('a', [], []) print(sort)
294
0
'''simple docstring''' __lowercase : Optional[int] = tuple[float, float, float] __lowercase : Optional[Any] = tuple[float, float, float] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any ): __a : Union[str, Any] = end_pointa[0] - end_pointa[0] __a : Dict = end_pointa[1] - end_pointa[1] __a : int = end_pointa[2] - end_pointa[2] return (x, y, z) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int ): __a : Union[str, Any] = ab[1] * ac[2] - ab[2] * ac[1] # *i __a : Any = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j __a : str = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] ): return tuple(round(_A , _A ) for x in vector ) == (0, 0, 0) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int = 10 ): __a : Dict = create_vector(_A , _A ) __a : Optional[int] = create_vector(_A , _A ) return is_zero_vector(get_ad_vectors_cross(_A , _A ) , _A )
358
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __UpperCamelCase ( SCREAMING_SNAKE_CASE__ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A__ , 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(A__ , 'num_attention_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=3 , __a=2 , __a=1 , __a=16 , __a=[128, 256, 384] , __a=[4, 6, 8] , __a=[2, 3, 4] , __a=[16, 16, 16] , __a=0 , __a=[2, 2, 2] , __a=[2, 2, 2] , __a=0.02 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : Union[str, Any] = parent __a : List[Any] = batch_size __a : Dict = image_size __a : List[str] = num_channels __a : List[Any] = kernel_size __a : Optional[Any] = stride __a : List[Any] = padding __a : Union[str, Any] = hidden_sizes __a : Union[str, Any] = num_attention_heads __a : Tuple = depths __a : List[Any] = key_dim __a : Dict = drop_path_rate __a : str = patch_size __a : int = attention_ratio __a : Any = mlp_ratio __a : Any = initializer_range __a : List[str] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] __a : Tuple = is_training __a : Optional[Any] = use_labels __a : List[Any] = num_labels __a : List[str] = initializer_range def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[Any] = None if self.use_labels: __a : Tuple = ids_tensor([self.batch_size] , self.num_labels ) __a : Optional[Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : str = LevitModel(config=A__ ) model.to(A__ ) model.eval() __a : Optional[Any] = model(A__ ) __a : Tuple = (self.image_size, self.image_size) __a , __a : str = image_size[0], image_size[1] for _ in range(4 ): __a : str = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) __a : List[str] = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Tuple = self.num_labels __a : Optional[int] = LevitForImageClassification(A__ ) model.to(A__ ) model.eval() __a : Union[str, Any] = model(A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): A_ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) A_ = ( { '''feature-extraction''': LevitModel, '''image-classification''': (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LevitModelTester(self ) __a : int = ConfigTester(self , config_class=A__ , has_text_modality=A__ , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self ): '''simple docstring''' return @unittest.skip(reason='Levit does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Levit does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Levit does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Union[str, Any] = model_class(A__ ) __a : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , A__ ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : Union[str, Any] = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): __a : Union[str, Any] = model(**self._prepare_for_class(A__ , A__ ) ) __a : str = outputs.hidden_states __a : Any = len(self.model_tester.depths ) + 1 self.assertEqual(len(A__ ) , A__ ) __a : Tuple = (self.model_tester.image_size, self.model_tester.image_size) __a , __a : Dict = image_size[0], image_size[1] for _ in range(4 ): __a : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) __a : Tuple = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Optional[Any] = True check_hidden_states_output(A__ , A__ , A__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(A__ , A__ , A__ ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : int = super()._prepare_for_class(A__ , A__ , return_labels=A__ ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A__ ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.model_tester.is_training: return __a , __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __a : int = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(A__ ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue __a : int = model_class(A__ ) model.to(A__ ) model.train() __a : Tuple = self._prepare_for_class(A__ , A__ , return_labels=A__ ) __a : Optional[Any] = model(**A__ ).loss loss.backward() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __a : Optional[int] = False __a : int = True for model_class in self.all_model_classes: if model_class in get_values(A__ ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue __a : List[str] = model_class(A__ ) model.gradient_checkpointing_enable() model.to(A__ ) model.train() __a : int = self._prepare_for_class(A__ , A__ , return_labels=A__ ) __a : List[str] = model(**A__ ).loss loss.backward() def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : Union[str, Any] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(A__ ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type["title"]}""" ): __a : Optional[int] = problem_type['title'] __a : Dict = problem_type['num_labels'] __a : int = model_class(A__ ) model.to(A__ ) model.train() __a : List[str] = self._prepare_for_class(A__ , A__ , return_labels=A__ ) if problem_type["num_labels"] > 1: __a : Any = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) __a : Dict = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=A__ ) as warning_list: __a : Dict = model(**A__ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = LevitModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) def lowerCamelCase (): __a : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( A__ ) __a : Dict = self.default_image_processor __a : Tuple = prepare_img() __a : Optional[Any] = image_processor(images=A__ , return_tensors='pt' ).to(A__ ) # forward pass with torch.no_grad(): __a : Any = model(**A__ ) # verify the logits __a : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , A__ ) __a : str = torch.tensor([1.0448, -0.3745, -1.8317] ).to(A__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A__ , atol=1E-4 ) )
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration __lowercase : Tuple = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] __lowercase : List[Any] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] __lowercase : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) __lowercase : List[str] = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) __lowercase : Dict = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple ): for tf_name, hf_name in patterns: __a : Any = k.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return k def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Dict = BigBirdPegasusConfig(**_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = BigBirdPegasusForConditionalGeneration(_SCREAMING_SNAKE_CASE ) __a : Any = torch_model.state_dict() __a : Dict = {} # separating decoder weights __a : str = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} __a : Optional[int] = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): __a : str = [k.endswith(_SCREAMING_SNAKE_CASE ) for ending in KEYS_TO_IGNORE] if any(_SCREAMING_SNAKE_CASE ): continue __a : int = DECODER_PATTERNS __a : Dict = rename_state_dict_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_k not in state_dict: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): __a : List[Any] = v.T __a : List[Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): __a : str = [k.endswith(_SCREAMING_SNAKE_CASE ) for ending in KEYS_TO_IGNORE] if any(_SCREAMING_SNAKE_CASE ): continue __a : Any = REMAINING_PATTERNS __a : Union[str, Any] = rename_state_dict_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): __a : Dict = v.T __a : Optional[Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" __a : Union[str, Any] = mapping['model.embed_positions.weight'] __a : Optional[Any] = mapping.pop('model.embed_positions.weight' ) __a , __a : Optional[Any] = torch_model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : Optional[int] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : str = {} __a : int = ['global_step'] for name, shape in tqdm(_SCREAMING_SNAKE_CASE , desc='converting tf checkpoint to dict' ): __a : List[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue __a : Dict = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : List[Any] = array return tf_weights def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple ): __a : int = get_tf_weights_as_numpy(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = convert_bigbird_pegasus(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) torch_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') __lowercase : List[str] = parser.parse_args() __lowercase : Union[str, Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
360
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = 'laion/clap-htsat-unfused' __a : Optional[Any] = tempfile.mkdtemp() def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.get_tokenizer() __a : List[str] = self.get_feature_extractor() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) __a : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __a : List[str] = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) __a : Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : int = self.get_tokenizer() __a : str = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : int = floats_list((3, 1000) ) __a : str = feature_extractor(__a , return_tensors='np' ) __a : int = processor(audios=__a , 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 __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.get_feature_extractor() __a : Any = self.get_tokenizer() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Union[str, Any] = 'This is a test string' __a : Union[str, Any] = processor(text=__a ) __a : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : str = self.get_tokenizer() __a : List[str] = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a : Optional[int] = processor.batch_decode(__a ) __a : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.get_feature_extractor() __a : Optional[int] = self.get_tokenizer() __a : int = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
294
0
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=2 , __a=56 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=2 , __a=2 , __a=7 , __a="gelu_new" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=4 , __a="block_sparse" , __a=True , __a=False , __a=2 , __a=3 , ): '''simple docstring''' __a : List[Any] = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : Optional[int] = is_training __a : Optional[Any] = use_attention_mask __a : Dict = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : List[Any] = hidden_size __a : Tuple = num_hidden_layers __a : Any = num_attention_heads __a : int = intermediate_size __a : List[Any] = hidden_act __a : Optional[Any] = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Tuple = type_sequence_label_size __a : Any = initializer_range __a : List[Any] = num_choices __a : str = rescale_embeddings __a : Any = attention_type __a : Optional[int] = use_bias __a : Optional[Any] = block_size __a : Any = num_random_blocks def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_attention_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __a : Any = None if self.use_token_type_ids: __a : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : str = BigBirdConfig( 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=__A , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.prepare_config_and_inputs() __a : List[str] = config_and_inputs __a : Optional[int] = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask, } return config, inputs_dict @require_flax class __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): A_ = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self ): '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self ): '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self ): '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self ): '''simple docstring''' super().test_hidden_states_output() @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: __a : List[str] = model_class_name.from_pretrained('google/bigbird-roberta-base' ) self.assertIsNotNone(__A ) def __UpperCAmelCase ( self ): '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a : Any = self._prepare_for_class(__A , __A ) __a : Optional[Any] = model_class(__A ) @jax.jit def model_jitted(__a , __a=None , **__a ): return model(input_ids=__A , attention_mask=__A , **__A ) with self.subTest('JIT Enabled' ): __a : List[Any] = model_jitted(**__A ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __a : str = model_jitted(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) ) for jitted_output, output in zip(__A , __A ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCAmelCase ( self , __a , __a , __a , __a=1E-5 , __a="outputs" , __a=None ): '''simple docstring''' if name.startswith('outputs.attentions' ): return else: super().check_pt_flax_outputs(__A , __A , __A , __A , __A , __A )
361
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : List[str] = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : List[str] = num_hidden_layers __a : str = num_attention_heads __a : Optional[int] = intermediate_size __a : Tuple = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[int] = max_position_embeddings __a : Dict = type_vocab_size __a : Any = type_sequence_label_size __a : Dict = initializer_range __a : Optional[Any] = num_labels __a : Optional[Any] = num_choices __a : Union[str, Any] = relative_attention __a : List[str] = position_biased_input __a : List[Any] = pos_att_type __a : Tuple = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Any = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[int] = None __a : int = None __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __a : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a )[0] __a : str = model(__a , token_type_ids=__a )[0] __a : Optional[int] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : int = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : List[Any] = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __a : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : str = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __a : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) A_ = True A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = DebertaVaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __a : Optional[Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : int = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __a : str = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
294
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __lowercase : List[str] = '\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n' __lowercase : List[Any] = '\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n' __lowercase : int = '\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n \'score\' (float): The chrF (chrF++) score,\n \'char_order\' (int): The character n-gram order,\n \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n \'beta\' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( self ): '''simple docstring''' if version.parse(scb.__version__ ) < version.parse('1.4.12' ): raise ImportWarning( 'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n' 'You can install it with `pip install "sacrebleu>=1.4.12"`.' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/mjpost/sacreBLEU#chrf--chrf' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Sequence(datasets.Value('string' , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/mjpost/sacreBLEU#chrf--chrf'] , reference_urls=[ 'https://github.com/m-popovic/chrF', ] , ) def __UpperCAmelCase ( self , __a , __a , __a = CHRF.CHAR_ORDER , __a = CHRF.WORD_ORDER , __a = CHRF.BETA , __a = False , __a = False , __a = False , ): '''simple docstring''' __a : List[Any] = len(references[0] ) if any(len(__a ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) __a : List[Any] = [[refs[i] for refs in references] for i in range(__a )] __a : List[Any] = CHRF(__a , __a , __a , __a , __a , __a ) __a : int = sb_chrf.corpus_score(__a , __a ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
362
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if is_torch_version('<' , '2.0.0' ) or not hasattr(_SCREAMING_SNAKE_CASE , '_dynamo' ): return False return isinstance(_SCREAMING_SNAKE_CASE , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : bool = True ): __a : int = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a : Any = is_compiled_module(_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[Any] = model __a : Union[str, Any] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = model.module if not keep_fpaa_wrapper: __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'forward' ) __a : str = model.__dict__.pop('_original_forward' , _SCREAMING_SNAKE_CASE ) if original_forward is not None: while hasattr(_SCREAMING_SNAKE_CASE , '__wrapped__' ): __a : Any = forward.__wrapped__ if forward == original_forward: break __a : str = forward if getattr(_SCREAMING_SNAKE_CASE , '_converted_to_transformer_engine' , _SCREAMING_SNAKE_CASE ): convert_model(_SCREAMING_SNAKE_CASE , to_transformer_engine=_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[str] = model __a : Optional[int] = compiled_model return model def lowerCamelCase (): PartialState().wait_for_everyone() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif PartialState().local_process_index == 0: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @contextmanager def lowerCamelCase (**_SCREAMING_SNAKE_CASE : Tuple ): for key, value in kwargs.items(): __a : Optional[int] = str(_SCREAMING_SNAKE_CASE ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ) and not hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , '__class__' , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ): return obj.__qualname__ if hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): return obj.__name__ return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): for key, value in source.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : int = destination.setdefault(_SCREAMING_SNAKE_CASE , {} ) merge_dicts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a : Tuple = value return destination def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = None ): if port is None: __a : List[str] = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
294
0
'''simple docstring''' from ... import PretrainedConfig __lowercase : Optional[Any] = { 'sijunhe/nezha-cn-base': 'https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json', } class __UpperCamelCase ( _snake_case ): A_ = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP A_ = "nezha" def __init__( self , __a=2_1128 , __a=768 , __a=12 , __a=12 , __a=3072 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=64 , __a=2 , __a=0.02 , __a=1E-1_2 , __a=0.1 , __a=0 , __a=2 , __a=3 , __a=True , **__a , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __a : Union[str, Any] = vocab_size __a : Optional[int] = hidden_size __a : str = num_hidden_layers __a : int = num_attention_heads __a : int = hidden_act __a : Union[str, Any] = intermediate_size __a : Optional[Any] = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Tuple = max_relative_position __a : Union[str, Any] = type_vocab_size __a : List[str] = initializer_range __a : Any = layer_norm_eps __a : Dict = classifier_dropout __a : Any = use_cache
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
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 : int = { 'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RemBertConfig', 'RemBertOnnxConfig'] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Tuple = ['RemBertTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = ['RemBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = [ 'REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RemBertForCausalLM', 'RemBertForMaskedLM', 'RemBertForMultipleChoice', 'RemBertForQuestionAnswering', 'RemBertForSequenceClassification', 'RemBertForTokenClassification', 'RemBertLayer', 'RemBertModel', 'RemBertPreTrainedModel', 'load_tf_weights_in_rembert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = [ 'TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRemBertForCausalLM', 'TFRemBertForMaskedLM', 'TFRemBertForMultipleChoice', 'TFRemBertForQuestionAnswering', 'TFRemBertForSequenceClassification', 'TFRemBertForTokenClassification', 'TFRemBertLayer', 'TFRemBertModel', 'TFRemBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys __lowercase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
364
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class __UpperCamelCase : A_ = 42 A_ = None A_ = None def lowerCamelCase (_SCREAMING_SNAKE_CASE : TreeNode | None ): # Validation def is_valid_tree(_SCREAMING_SNAKE_CASE : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_SCREAMING_SNAKE_CASE ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( _SCREAMING_SNAKE_CASE : TreeNode | None , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _SCREAMING_SNAKE_CASE , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _SCREAMING_SNAKE_CASE ) ) return is_binary_search_tree_recursive_check(_SCREAMING_SNAKE_CASE , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __UpperCamelCase ( a__ ): A_ = ["image_processor", "tokenizer"] A_ = "AutoImageProcessor" A_ = "AutoTokenizer" def __init__( self , __a , __a ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __a : Optional[Any] = self.image_processor def __call__( self , __a=None , __a=None , __a=None , **__a ): '''simple docstring''' if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __a : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if images is not None: __a : int = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None and images is not None: __a : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) , tensor_type=SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
365
'''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. __lowercase : Dict = 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 (_SCREAMING_SNAKE_CASE : Optional[Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): from transformers.testing_utils import pytest_terminal_summary_main __a : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE , id=_SCREAMING_SNAKE_CASE )
294
0
'''simple docstring''' from collections.abc import Generator from math import sin def lowerCamelCase (_SCREAMING_SNAKE_CASE : bytes ): if len(lowerCAmelCase__ ) != 32: raise ValueError('Input must be of length 32' ) __a : List[Any] = B'' for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): if i < 0: raise ValueError('Input must be non-negative' ) __a : List[Any] = format(lowerCAmelCase__ , '08x' )[-8:] __a : str = B'' for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('utf-8' ) return little_endian_hex def lowerCamelCase (_SCREAMING_SNAKE_CASE : bytes ): __a : Union[str, Any] = B'' for char in message: bit_string += format(lowerCAmelCase__ , '08b' ).encode('utf-8' ) __a : Any = format(len(lowerCAmelCase__ ) , '064b' ).encode('utf-8' ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(lowerCAmelCase__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def lowerCamelCase (_SCREAMING_SNAKE_CASE : bytes ): if len(lowerCAmelCase__ ) % 512 != 0: raise ValueError('Input must have length that\'s a multiple of 512' ) for pos in range(0 , len(lowerCAmelCase__ ) , 512 ): __a : str = bit_string[pos : pos + 512] __a : int = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): if i < 0: raise ValueError('Input must be non-negative' ) __a : Optional[Any] = format(lowerCAmelCase__ , '032b' ) __a : int = '' for c in i_str: new_str += "1" if c == "0" else "0" return int(lowerCAmelCase__ , 2 ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): return (a + b) % 2**32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if i < 0: raise ValueError('Input must be non-negative' ) if shift < 0: raise ValueError('Shift must be non-negative' ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def lowerCamelCase (_SCREAMING_SNAKE_CASE : bytes ): __a : str = preprocess(lowerCAmelCase__ ) __a : Dict = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states __a : Optional[int] = 0X67_45_23_01 __a : str = 0Xef_cd_ab_89 __a : Tuple = 0X98_ba_dc_fe __a : List[str] = 0X10_32_54_76 __a : Union[str, Any] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(lowerCAmelCase__ ): __a : Optional[Any] = aa __a : Dict = ba __a : Tuple = ca __a : Optional[Any] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f __a : Tuple = d ^ (b & (c ^ d)) __a : Optional[int] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f __a : int = c ^ (d & (b ^ c)) __a : List[str] = (5 * i + 1) % 16 elif i <= 47: __a : List[Any] = b ^ c ^ d __a : List[Any] = (3 * i + 5) % 16 else: __a : Dict = c ^ (b | not_aa(lowerCAmelCase__ )) __a : List[Any] = (7 * i) % 16 __a : int = (f + a + added_consts[i] + block_words[g]) % 2**32 __a : Tuple = d __a : Optional[Any] = c __a : Dict = b __a : Dict = sum_aa(lowerCAmelCase__ , left_rotate_aa(lowerCAmelCase__ , shift_amounts[i] ) ) # Add hashed chunk to running total __a : int = sum_aa(lowerCAmelCase__ , lowerCAmelCase__ ) __a : Any = sum_aa(lowerCAmelCase__ , lowerCAmelCase__ ) __a : Optional[int] = sum_aa(lowerCAmelCase__ , lowerCAmelCase__ ) __a : int = sum_aa(lowerCAmelCase__ , lowerCAmelCase__ ) __a : List[str] = reformat_hex(lowerCAmelCase__ ) + reformat_hex(lowerCAmelCase__ ) + reformat_hex(lowerCAmelCase__ ) + reformat_hex(lowerCAmelCase__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
366
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): re.sub('<n>' , '' , _SCREAMING_SNAKE_CASE ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_SCREAMING_SNAKE_CASE ) )
294
0
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar __lowercase : Any = TypeVar('KT') __lowercase : Optional[int] = TypeVar('VT') class __UpperCamelCase ( Generic[KT, VT] ): def __init__( self , __a = "root" , __a = None ): '''simple docstring''' __a : Any = key __a : Optional[int] = value __a : list[Node[KT, VT]] = [] def __repr__( self ): '''simple docstring''' return f"""Node({self.key}: {self.value})""" @property def __UpperCAmelCase ( self ): '''simple docstring''' return len(self.forward ) class __UpperCamelCase ( Generic[KT, VT] ): def __init__( self , __a = 0.5 , __a = 16 ): '''simple docstring''' __a : Node[KT, VT] = Node[KT, VT]() __a : str = 0 __a : List[Any] = p __a : Optional[int] = max_level def __str__( self ): '''simple docstring''' __a : List[Any] = list(self ) if len(__lowercase ) == 0: return f"""SkipList(level={self.level})""" __a : List[str] = max((len(str(__lowercase ) ) for item in items) , default=4 ) __a : Union[str, Any] = max(__lowercase , 4 ) + 4 __a : Optional[int] = self.head __a : Optional[Any] = [] __a : List[str] = node.forward.copy() lines.append(f"""[{node.key}]""".ljust(__lowercase , '-' ) + '* ' * len(__lowercase ) ) lines.append(' ' * label_size + '| ' * len(__lowercase ) ) while len(node.forward ) != 0: __a : Tuple = node.forward[0] lines.append( f"""[{node.key}]""".ljust(__lowercase , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(__lowercase ) ) __a : List[str] = node.forward lines.append('None'.ljust(__lowercase ) + '* ' * len(__lowercase ) ) return f"""SkipList(level={self.level})\n""" + "\n".join(__lowercase ) def __iter__( self ): '''simple docstring''' __a : Optional[int] = self.head while len(node.forward ) != 0: yield node.forward[0].key __a : Optional[Any] = node.forward[0] def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = 1 while random() < self.p and level < self.max_level: level += 1 return level def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : List[Any] = [] __a : Dict = 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: __a : int = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(__lowercase ) 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 __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Optional[int] = self._locate_node(__lowercase ) if node is not None: for i, update_node in enumerate(__lowercase ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: __a : Dict = node.forward[i] else: __a : List[str] = update_node.forward[:i] def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : Dict = self._locate_node(__lowercase ) if node is not None: __a : Tuple = value else: __a : Union[str, Any] = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , __lowercase ): update_vector.append(self.head ) __a : Optional[int] = level __a : List[str] = Node(__lowercase , __lowercase ) 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(__lowercase ) else: __a : Optional[int] = new_node def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = self._locate_node(__lowercase ) if node is not None: return node.value return None def lowerCamelCase (): __a : List[str] = SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) __a : Optional[Any] = skip_list.head __a : List[str] = {} while node.level != 0: __a : str = node.forward[0] __a : Optional[int] = node.value assert len(_SCREAMING_SNAKE_CASE ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowerCamelCase (): __a : int = 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 ) __a : int = skip_list.head __a : Optional[Any] = {} while node.level != 0: __a : Union[str, Any] = node.forward[0] __a : Any = node.value if len(_SCREAMING_SNAKE_CASE ) != 4: print() assert len(_SCREAMING_SNAKE_CASE ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowerCamelCase (): __a : Any = SkipList() assert skip_list.find('Some key' ) is None def lowerCamelCase (): __a : List[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 (): __a : Union[str, Any] = SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def lowerCamelCase (): __a : 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' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def lowerCamelCase (): __a : 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 (): __a : Union[str, 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(_SCREAMING_SNAKE_CASE : List[str] ): yield node.key for forward_node in node.forward: yield from traverse_keys(_SCREAMING_SNAKE_CASE ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowerCamelCase (): def is_sorted(_SCREAMING_SNAKE_CASE : List[str] ): return all(next_item >= item for item, next_item in zip(_SCREAMING_SNAKE_CASE , lst[1:] ) ) __a : Dict = SkipList() for i in range(10 ): skip_list.insert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert is_sorted(list(_SCREAMING_SNAKE_CASE ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_SCREAMING_SNAKE_CASE ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_SCREAMING_SNAKE_CASE ) ) def lowerCamelCase (): 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 (): __a : Union[str, Any] = 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(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() main()
367
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowercase : Any = [0, 25, 50] __lowercase : int = [25, 50, 75] __lowercase : List[str] = fuzz.membership.trimf(X, abca) __lowercase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowercase : List[Any] = np.ones(75) __lowercase : Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowercase : str = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowercase : List[Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowercase : Optional[Any] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowercase : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowercase : Optional[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowercase : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
294
0
'''simple docstring''' from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration __lowercase : List[str] = HfArgumentParser(InitializationArguments) __lowercase : int = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization __lowercase : List[str] = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks __lowercase : Optional[Any] = { 'vocab_size': len(tokenizer), 'scale_attn_by_inverse_layer_idx': True, 'reorder_and_upcast_attn': True, } # Load model config (GPT-2 large in this case) __lowercase : int = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config __lowercase : Dict = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
368
'''simple docstring''' import sys __lowercase : Union[str, Any] = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : List[str] = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = N ): __a : Optional[int] = -sys.maxsize - 1 __a : Optional[Any] = n[:13] __a : int = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): __a : List[Any] = substr[1:] + n[cur_index] cur_index += 1 else: __a : Dict = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) __a : Optional[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
294
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __lowercase : str = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class __UpperCamelCase ( _UpperCamelCase ): A_ = 'albert' def __init__( self , __a=3_0000 , __a=128 , __a=4096 , __a=12 , __a=1 , __a=64 , __a=1_6384 , __a=1 , __a="gelu_new" , __a=0 , __a=0 , __a=512 , __a=2 , __a=0.02 , __a=1E-1_2 , __a=0.1 , __a="absolute" , __a=0 , __a=2 , __a=3 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) __a : Optional[Any] = vocab_size __a : List[str] = embedding_size __a : Union[str, Any] = hidden_size __a : List[Any] = num_hidden_layers __a : List[Any] = num_hidden_groups __a : int = num_attention_heads __a : List[str] = inner_group_num __a : int = hidden_act __a : Optional[int] = intermediate_size __a : List[str] = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : str = type_vocab_size __a : str = initializer_range __a : Tuple = layer_norm_eps __a : List[str] = classifier_dropout_prob __a : str = position_embedding_type class __UpperCamelCase ( _UpperCamelCase ): @property def __UpperCAmelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": __a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Union[str, Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
369
'''simple docstring''' import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = CodeGenTokenizer A_ = CodeGenTokenizerFast A_ = True A_ = {"add_prefix_space": True} A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __a : Tuple = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __a : Union[str, Any] = dict(zip(__a , range(len(__a ) ) ) ) __a : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __a : Dict = {'unk_token': '<unk>'} __a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__a ) ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Tuple = 'lower newer' __a : Tuple = 'lower newer' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __a : str = 'lower newer' __a : Tuple = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) self.assertListEqual(__a , __a ) __a : List[str] = tokens + [tokenizer.unk_token] __a : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Any = 'lower newer' # Testing tokenization __a : Dict = tokenizer.tokenize(__a , add_prefix_space=__a ) __a : Dict = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids without special tokens __a : int = tokenizer.encode(__a , add_special_tokens=__a , add_prefix_space=__a ) __a : Tuple = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) # Testing conversion to ids with special tokens __a : Tuple = self.get_rust_tokenizer(add_prefix_space=__a ) __a : Union[str, Any] = tokenizer.encode(__a , add_prefix_space=__a ) __a : int = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # Testing the unknown token __a : Any = tokens + [rust_tokenizer.unk_token] __a : Tuple = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__a ) , __a ) def __UpperCAmelCase ( self , *__a , **__a ): '''simple docstring''' pass def __UpperCAmelCase ( self , __a=15 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : Optional[int] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) # Simple input __a : List[Any] = 'This is a simple input' __a : Tuple = ['This is a simple input 1', 'This is a simple input 2'] __a : Tuple = ('This is a simple input', 'This is a pair') __a : str = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Simple input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) # Pair input self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='max_length' ) # Pair input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='max_length' , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __a : str = 'This is a simple input' __a : Any = ['This is a simple input looooooooong', 'This is a simple input'] __a : Optional[int] = ('This is a simple input', 'This is a pair') __a : Optional[Any] = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __a : int = tokenizer.pad_token_id __a : List[Any] = tokenizer(__a , padding='max_length' , max_length=30 , return_tensors='np' ) __a : Union[str, Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) __a : Optional[Any] = tokenizer(*__a , padding='max_length' , max_length=60 , return_tensors='np' ) __a : List[Any] = tokenizer(__a , padding=__a , truncate=__a , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = '$$$' __a : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__a , add_bos_token=__a ) __a : Union[str, Any] = 'This is a simple input' __a : List[Any] = ['This is a simple input 1', 'This is a simple input 2'] __a : List[Any] = tokenizer.bos_token_id __a : List[str] = tokenizer(__a ) __a : Optional[Any] = tokenizer(__a ) self.assertEqual(out_s.input_ids[0] , __a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __a : Any = tokenizer.decode(out_s.input_ids ) __a : Union[str, Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' ) __a : Optional[int] = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' __a : Tuple = '\nif len_a > len_b: result = a\nelse: result = b' __a : Optional[int] = tokenizer.encode(__a ) __a : Union[str, Any] = ['^#', re.escape('<|endoftext|>' ), '^\'\'\'', '^"""', '\n\n\n'] __a : Tuple = tokenizer.decode(__a , truncate_before_pattern=__a ) self.assertEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' pass
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Any ): # 1. Validate that path exists between current and next vertices 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 (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str ): # Base Case if curr_ind == len(__SCREAMING_SNAKE_CASE ): # 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(__SCREAMING_SNAKE_CASE ) ): if valid_connection(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Insert current vertex into path as next transition __a : List[str] = next_ver # Validate created path if util_hamilton_cycle(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , curr_ind + 1 ): return True # Backtrack __a : List[Any] = -1 return False def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] = 0 ): __a : Any = [-1] * (len(__SCREAMING_SNAKE_CASE ) + 1) # initialize start and end of path with starting index __a : Union[str, Any] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 1 ) else []
370
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError('iterations must be defined as integers' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) __a : Dict = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_SCREAMING_SNAKE_CASE ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __lowercase : List[str] = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': 10_00, '''block_out_channels''': [32, 64], '''attention_head_dim''': 8, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowercase : Optional[int] = { '''sample_size''': 64, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 3, '''num_class_embeds''': 10_00, '''block_out_channels''': [1_92, 1_92 * 2, 1_92 * 3, 1_92 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowercase : Any = { '''sample_size''': 2_56, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': None, '''block_out_channels''': [2_56, 2_56, 2_56 * 2, 2_56 * 2, 2_56 * 4, 2_56 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''default''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } __lowercase : List[Any] = { '''num_train_timesteps''': 40, '''sigma_min''': 0.0_02, '''sigma_max''': 80.0, } __lowercase : Optional[Any] = { '''num_train_timesteps''': 2_01, '''sigma_min''': 0.0_02, '''sigma_max''': 80.0, } __lowercase : Dict = { '''num_train_timesteps''': 1_51, '''sigma_min''': 0.0_02, '''sigma_max''': 80.0, } def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('boolean value expected' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str]=False ): __a : Tuple = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] __a : Dict = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] __a : Any = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] __a : Tuple = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] __a : Optional[Any] = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] __a : Optional[Any] = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] __a : Optional[int] = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] __a : int = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] __a : Tuple = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] __a : List[str] = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: __a : Union[str, Any] = checkpoint[F"""{old_prefix}.skip_connection.weight"""] __a : str = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int]=None ): __a , __a , __a : Optional[Any] = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) __a , __a , __a : Tuple = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) __a : Dict = checkpoint[F"""{old_prefix}.norm.weight"""] __a : str = checkpoint[F"""{old_prefix}.norm.bias"""] __a : List[str] = weight_q.squeeze(-1 ).squeeze(-1 ) __a : List[Any] = bias_q.squeeze(-1 ).squeeze(-1 ) __a : Any = weight_k.squeeze(-1 ).squeeze(-1 ) __a : List[Any] = bias_k.squeeze(-1 ).squeeze(-1 ) __a : Tuple = weight_v.squeeze(-1 ).squeeze(-1 ) __a : Dict = bias_v.squeeze(-1 ).squeeze(-1 ) __a : Dict = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) __a : Dict = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int ): __a : int = torch.load(__lowerCAmelCase , map_location='cpu' ) __a : List[str] = {} __a : Optional[int] = checkpoint['time_embed.0.weight'] __a : str = checkpoint['time_embed.0.bias'] __a : Optional[Any] = checkpoint['time_embed.2.weight'] __a : List[str] = checkpoint['time_embed.2.bias'] if unet_config["num_class_embeds"] is not None: __a : str = checkpoint['label_emb.weight'] __a : List[str] = checkpoint['input_blocks.0.0.weight'] __a : Any = checkpoint['input_blocks.0.0.bias'] __a : Union[str, Any] = unet_config['down_block_types'] __a : int = unet_config['layers_per_block'] __a : Optional[int] = unet_config['attention_head_dim'] __a : List[str] = unet_config['block_out_channels'] __a : List[str] = 1 __a : List[str] = channels_list[0] for i, layer_type in enumerate(__lowerCAmelCase ): __a : Tuple = channels_list[i] __a : Optional[Any] = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(__lowerCAmelCase ): __a : List[str] = F"""down_blocks.{i}.resnets.{j}""" __a : Optional[Any] = F"""input_blocks.{current_layer}.0""" __a : str = True if j == 0 and downsample_block_has_skip else False __a : List[str] = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , has_skip=__lowerCAmelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(__lowerCAmelCase ): __a : Dict = F"""down_blocks.{i}.resnets.{j}""" __a : Union[str, Any] = F"""input_blocks.{current_layer}.0""" __a : int = True if j == 0 and downsample_block_has_skip else False __a : int = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , has_skip=__lowerCAmelCase ) __a : int = F"""down_blocks.{i}.attentions.{j}""" __a : Dict = F"""input_blocks.{current_layer}.1""" __a : List[str] = convert_attention( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) current_layer += 1 if i != len(__lowerCAmelCase ) - 1: __a : Optional[int] = F"""down_blocks.{i}.downsamplers.0""" __a : Dict = F"""input_blocks.{current_layer}.0""" __a : str = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) current_layer += 1 __a : Any = current_channels # hardcoded the mid-block for now __a : List[str] = 'mid_block.resnets.0' __a : Optional[int] = 'middle_block.0' __a : Optional[int] = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __a : str = 'mid_block.attentions.0' __a : Any = 'middle_block.1' __a : List[Any] = convert_attention(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __a : List[str] = 'mid_block.resnets.1' __a : str = 'middle_block.2' __a : Optional[Any] = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __a : List[Any] = 0 __a : Dict = unet_config['up_block_types'] for i, layer_type in enumerate(__lowerCAmelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): __a : Any = F"""up_blocks.{i}.resnets.{j}""" __a : Tuple = F"""output_blocks.{current_layer}.0""" __a : int = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , has_skip=__lowerCAmelCase ) current_layer += 1 if i != len(__lowerCAmelCase ) - 1: __a : int = F"""up_blocks.{i}.upsamplers.0""" __a : Dict = F"""output_blocks.{current_layer-1}.1""" __a : List[Any] = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): __a : str = F"""up_blocks.{i}.resnets.{j}""" __a : Dict = F"""output_blocks.{current_layer}.0""" __a : Any = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , has_skip=__lowerCAmelCase ) __a : Optional[Any] = F"""up_blocks.{i}.attentions.{j}""" __a : Union[str, Any] = F"""output_blocks.{current_layer}.1""" __a : str = convert_attention( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) current_layer += 1 if i != len(__lowerCAmelCase ) - 1: __a : Any = F"""up_blocks.{i}.upsamplers.0""" __a : str = F"""output_blocks.{current_layer-1}.2""" __a : List[str] = convert_resnet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __a : Tuple = checkpoint['out.0.weight'] __a : Optional[Any] = checkpoint['out.0.bias'] __a : int = checkpoint['out.2.weight'] __a : List[str] = checkpoint['out.2.bias'] return new_checkpoint if __name__ == "__main__": __lowercase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--unet_path', default=None, type=str, required=True, help='Path to the unet.pt to convert.') parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output the converted UNet model.' ) parser.add_argument('--class_cond', default=True, type=str, help='Whether the model is class-conditional.') __lowercase : Union[str, Any] = parser.parse_args() __lowercase : Dict = strabool(args.class_cond) __lowercase : Dict = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: __lowercase : Optional[Any] = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __lowercase : Optional[Any] = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: __lowercase : Optional[int] = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: __lowercase : List[Any] = None __lowercase : Union[str, Any] = con_pt_to_diffuser(args.unet_path, unet_config) __lowercase : Dict = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: __lowercase : Dict = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: __lowercase : List[Any] = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __lowercase : List[Any] = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') __lowercase : Dict = CMStochasticIterativeScheduler(**scheduler_config) __lowercase : Optional[Any] = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
371
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , ): '''simple docstring''' __a : List[Any] = size if size is not None else {'height': 18, 'width': 18} __a : int = parent __a : Dict = batch_size __a : Optional[int] = num_channels __a : List[Any] = image_size __a : Tuple = min_resolution __a : str = max_resolution __a : str = do_resize __a : Optional[Any] = size __a : str = apply_ocr def __UpperCAmelCase ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LayoutLMvaImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'apply_ocr' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __a : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched __a : Any = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : Tuple = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __a : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : List[str] = image_processing(__a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __a : str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) __a : Tuple = Image.open(ds[0]['file'] ).convert('RGB' ) __a : Optional[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a : Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 __a : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False __a : List[Any] = LayoutLMvaImageProcessor(apply_ocr=__a ) __a : List[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : list[int] ): # Check if the input is valid if not len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __a : Optional[int] = equationa __a : List[Any] = equationa # Calculate the determinants of the matrices __a : Dict = aa * ba - aa * ba __a : Union[str, Any] = ca * ba - ca * ba __a : str = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __a : Any = determinant_x / determinant __a : Union[str, Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
350
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
0
'''simple docstring''' from math import factorial __lowercase : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_SCREAMING_SNAKE_CASE ) ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 60 , _SCREAMING_SNAKE_CASE : int = 1_000_000 ): if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __a : Optional[Any] = 0 # the cached sizes of the previous chains __a : dict[int, int] = {} for start_chain_element in range(1 , _SCREAMING_SNAKE_CASE ): # The temporary set will contain the elements of the chain __a : Union[str, Any] = set() __a : Dict = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __a : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_SCREAMING_SNAKE_CASE ) chain_set_length += 1 __a : int = digit_factorial_sum(_SCREAMING_SNAKE_CASE ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __a : str = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution()}''')
351
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a ): '''simple docstring''' super().__init__() __a : int = module __a : List[Any] = nn.Sequential( nn.Linear(module.in_features , __a , bias=__a ) , nn.Linear(__a , module.out_features , bias=__a ) , ) __a : int = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=__a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def __UpperCAmelCase ( self , __a , *__a , **__a ): '''simple docstring''' return self.module(__a , *__a , **__a ) + self.adapter(__a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module A_ = "bigscience/bloom-1b7" # Constant values A_ = 2.109659552692574 A_ = "Hello my name is" A_ = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) A_ = 10 def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = AutoTokenizer.from_pretrained(self.model_name ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # Models and tokenizer __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_abit.config self.assertTrue(hasattr(__a , 'quantization_config' ) ) __a : Union[str, Any] = config.to_dict() __a : Tuple = config.to_diff_dict() __a : Tuple = config.to_json_string() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit __a : List[Any] = self.model_fpaa.get_memory_footprint() __a : List[Any] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __a : Tuple = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(__a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Union[str, Any] = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BitsAndBytesConfig() __a : Tuple = True __a : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ) __a : List[Any] = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = BitsAndBytesConfig() with self.assertRaises(__a ): __a : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , load_in_abit=__a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def __UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(__a ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(__a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(__a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __a : List[str] = self.tokenizer(self.input_text , return_tensors='pt' ) __a : Optional[int] = self.model_fpaa.to(torch.floataa ) __a : Tuple = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __a : List[Any] = self.model_fpaa.to('cpu' ) # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.half() # Check this does not throw an error __a : Union[str, Any] = self.model_fpaa.float() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=__a , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __UpperCamelCase ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ): '''simple docstring''' __a : Any = 't5-small' __a : Tuple = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __a : int = AutoTokenizer.from_pretrained(cls.model_name ) __a : Union[str, Any] = 'Translate in German: Hello, my dog is cute' def __UpperCAmelCase ( self ): '''simple docstring''' gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from transformers import TaForConditionalGeneration __a : Optional[int] = TaForConditionalGeneration._keep_in_fpaa_modules __a : List[str] = None # test with `t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[int] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : Any = model.generate(**__a ) # test with `flan-t5-small` __a : List[str] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[Any] = model.generate(**__a ) __a : Optional[int] = modules def __UpperCAmelCase ( self ): '''simple docstring''' import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __a : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : List[str] = model.generate(**__a ) # test with `flan-t5-small` __a : List[Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map='auto' ) __a : Optional[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __a : int = model.generate(**__a ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() # model_name __a : List[Any] = 'bigscience/bloom-560m' __a : Union[str, Any] = 't5-small' # Different types of model __a : Optional[Any] = AutoModel.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Sequence classification model __a : Dict = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=__a , device_map='auto' ) # CausalLM model __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map='auto' ) # Seq2seq model __a : Any = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=__a , device_map='auto' ) def __UpperCAmelCase ( self ): '''simple docstring''' del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' del self.pipe gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __a : str = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=__a , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __a : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __a : str = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = 'facebook/opt-350m' super().setUp() def __UpperCAmelCase ( self ): '''simple docstring''' if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __a : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __a : Tuple = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __a : Tuple = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(__a ) ): __a : str = LoRALayer(module.q_proj , rank=16 ) __a : str = LoRALayer(module.k_proj , rank=16 ) __a : Optional[int] = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __a : List[str] = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __a : int = model.forward(**__a ) out.logits.norm().backward() for module in model.modules(): if isinstance(__a , __a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(__a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "gpt2-xl" A_ = 3.3191854854152187
294
0
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase : """simple docstring""" def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=24 , __a=2 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=None , __a=1000 , ): '''simple docstring''' __a : str = parent __a : Optional[int] = batch_size __a : List[Any] = seq_length __a : Dict = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Optional[int] = use_labels __a : List[str] = vocab_size __a : Dict = hidden_size __a : Union[str, Any] = num_hidden_layers __a : List[str] = num_attention_heads __a : Any = intermediate_size __a : Any = hidden_act __a : Optional[Any] = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Dict = max_position_embeddings __a : str = type_vocab_size __a : Dict = type_sequence_label_size __a : str = initializer_range __a : List[Any] = num_labels __a : str = scope __a : Tuple = range_bbox def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : int = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a : Optional[int] = bbox[i, j, 3] __a : Optional[int] = bbox[i, j, 1] __a : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: __a : Optional[int] = bbox[i, j, 2] __a : Optional[Any] = bbox[i, j, 0] __a : int = t __a : Any = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : List[Any] = None if self.use_token_type_ids: __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Tuple = None __a : int = None if self.use_labels: __a : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : str = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCAmelCase ( self ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ): '''simple docstring''' __a : Optional[int] = LiltModel(config=__a ) model.to(__a ) model.eval() __a : Any = model(__a , bbox=__a , attention_mask=__a , token_type_ids=__a ) __a : List[str] = model(__a , bbox=__a , token_type_ids=__a ) __a : Any = model(__a , bbox=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ): '''simple docstring''' __a : Optional[int] = self.num_labels __a : str = LiltForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model( __a , bbox=__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ): '''simple docstring''' __a : str = LiltForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : int = model( __a , bbox=__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.prepare_config_and_inputs() ( __a ) : Tuple = config_and_inputs __a : int = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" A_ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) A_ = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a , __a , __a ): '''simple docstring''' return True def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LiltModelTester(self ) __a : Union[str, Any] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a : Dict = type self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[int] = LiltModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @slow class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(__a ) __a : List[Any] = torch.tensor([[1, 2]] , device=__a ) __a : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__a ) # forward pass with torch.no_grad(): __a : Union[str, Any] = model(input_ids=__a , bbox=__a ) __a : Union[str, Any] = torch.Size([1, 2, 768] ) __a : Dict = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=__a , ) self.assertTrue(outputs.last_hidden_state.shape , __a ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __a , atol=1E-3 ) )
352
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __UpperCamelCase ( lowerCAmelCase_ ): A_ = None A_ = None A_ = None A_ = None class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a=1 , __a=0 , __a=2 , __a=512 , __a="cls" , __a=False , __a=True , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __a : Any = project_dim __a : Optional[Any] = pooler_fn __a : int = learn_encoder __a : str = use_attention_mask class __UpperCamelCase ( lowerCAmelCase_ ): A_ = [r"pooler", r"logit_scale"] A_ = [r"position_ids", r"predictions.decoder.bias"] A_ = "roberta" A_ = RobertaSeriesConfig def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Optional[Any] = XLMRobertaModel(__a ) __a : str = nn.Linear(config.hidden_size , config.project_dim ) __a : Optional[int] = getattr(__a , 'has_pre_transformation' , __a ) if self.has_pre_transformation: __a : int = nn.Linear(config.hidden_size , config.project_dim ) __a : List[str] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Tuple = self.base_model( input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , ) if self.has_pre_transformation: __a : Optional[Any] = outputs['hidden_states'][-2] __a : Optional[int] = self.pre_LN(__a ) __a : Union[str, Any] = self.transformation_pre(__a ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: __a : Optional[Any] = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
294
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowercase = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , *__a , **__a ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , __a , ) super().__init__(*__a , **__a )
353
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = BertTokenizer A_ = BertTokenizerFast A_ = True A_ = True A_ = filter_non_english def __UpperCAmelCase ( self ): '''simple docstring''' super().setUp() __a : Union[str, Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __a : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = 'UNwant\u00E9d,running' __a : List[str] = 'unwanted, running' return input_text, output_text def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.tokenizer_class(self.vocab_file ) __a : int = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def __UpperCAmelCase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return __a : Union[str, Any] = self.get_tokenizer() __a : Dict = self.get_rust_tokenizer() __a : int = 'UNwant\u00E9d,running' __a : Tuple = tokenizer.tokenize(__a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Tuple = tokenizer.encode(__a , add_special_tokens=__a ) __a : str = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : Dict = self.get_rust_tokenizer() __a : int = tokenizer.encode(__a ) __a : Tuple = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) # With lower casing __a : Optional[int] = self.get_tokenizer(do_lower_case=__a ) __a : Any = self.get_rust_tokenizer(do_lower_case=__a ) __a : List[str] = 'UNwant\u00E9d,running' __a : int = tokenizer.tokenize(__a ) __a : List[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) __a : Any = tokenizer.encode(__a , add_special_tokens=__a ) __a : str = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) __a : Dict = self.get_rust_tokenizer() __a : Optional[Any] = tokenizer.encode(__a ) __a : Optional[int] = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = BasicTokenizer() __a : Union[str, Any] = 'a\n\'ll !!to?\'d of, can\'t.' __a : Any = ['a', '\'', 'll', '!', '!', 'to', '?', '\'', 'd', 'of', ',', 'can', '\'', 't', '.'] self.assertListEqual(tokenizer.tokenize(__a ) , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __a : str = {} for i, token in enumerate(__a ): __a : Union[str, Any] = i __a : Dict = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.get_tokenizer() __a : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.tokenizer_class.from_pretrained('bert-base-uncased' ) __a : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __a : Tuple = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __a : Any = tokenizer.build_inputs_with_special_tokens(__a ) __a : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __UpperCAmelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : str = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : Dict = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __a : str = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) __a : Optional[int] = tokenizer_r.do_lower_case if hasattr(__a , 'do_lower_case' ) else False __a : int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = ['的', '人', '有'] __a : Optional[Any] = ''.join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a : List[Any] = True __a : Union[str, Any] = self.tokenizer_class.from_pretrained(__a , **__a ) __a : Tuple = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : Optional[int] = tokenizer_p.encode(__a , add_special_tokens=__a ) __a : str = tokenizer_r.encode(__a , add_special_tokens=__a ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(__a ) __a : Any = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) __a : Optional[int] = False __a : List[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) __a : List[Any] = self.tokenizer_class.from_pretrained(__a , **__a ) __a : Tuple = tokenizer_r.encode(__a , add_special_tokens=__a ) __a : Union[str, Any] = tokenizer_p.encode(__a , add_special_tokens=__a ) __a : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) __a : str = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". __a : int = [ f"""##{token}""" if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a )
354
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __lowercase : str = logging.get_logger(__name__) # General docstring __lowercase : List[str] = 'MobileNetV1Config' # Base docstring __lowercase : Tuple = 'google/mobilenet_v1_1.0_224' __lowercase : List[Any] = [1, 10_24, 7, 7] # Image classification docstring __lowercase : int = 'google/mobilenet_v1_1.0_224' __lowercase : Any = 'tabby, tabby cat' __lowercase : Dict = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any]=None ): __a : Dict = {} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = model.mobilenet_va else: __a : List[Any] = model __a : Dict = 'MobilenetV1/Conv2d_0/' __a : Dict = backbone.conv_stem.convolution.weight __a : Optional[Any] = backbone.conv_stem.normalization.bias __a : int = backbone.conv_stem.normalization.weight __a : int = backbone.conv_stem.normalization.running_mean __a : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): __a : int = i + 1 __a : Dict = i * 2 __a : Dict = backbone.layer[pt_index] __a : Dict = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" __a : Union[str, Any] = pointer.convolution.weight __a : Optional[Any] = pointer.normalization.bias __a : Union[str, Any] = pointer.normalization.weight __a : List[Any] = pointer.normalization.running_mean __a : Tuple = pointer.normalization.running_var __a : List[str] = backbone.layer[pt_index + 1] __a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" __a : Optional[int] = pointer.convolution.weight __a : List[str] = pointer.normalization.bias __a : Dict = pointer.normalization.weight __a : Dict = pointer.normalization.running_mean __a : Optional[int] = pointer.normalization.running_var if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Any = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __a : Optional[int] = model.classifier.weight __a : List[Any] = model.classifier.bias return tf_to_pt_map def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __a : Union[str, Any] = tf.train.list_variables(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) __a : List[str] = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[Any] = array # Build TF to PyTorch weights loading map __a : Optional[int] = _build_tf_to_pytorch_map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue __a : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __a : Optional[Any] = np.transpose(_SCREAMING_SNAKE_CASE , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __a : Union[str, Any] = array.squeeze().transpose() else: __a : Dict = np.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) __a : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) tf_weights.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/RMSProp_1' , _SCREAMING_SNAKE_CASE ) tf_weights.pop(name + '/ExponentialMovingAverage' , _SCREAMING_SNAKE_CASE ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def lowerCamelCase (_SCREAMING_SNAKE_CASE : torch.Tensor , _SCREAMING_SNAKE_CASE : nn.Convad ): __a , __a : Any = features.shape[-2:] __a , __a : int = conv_layer.stride __a , __a : Any = conv_layer.kernel_size if in_height % stride_height == 0: __a : int = max(kernel_height - stride_height , 0 ) else: __a : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __a : Any = max(kernel_width - stride_width , 0 ) else: __a : str = max(kernel_width - (in_width % stride_width) , 0 ) __a : int = pad_along_width // 2 __a : Dict = pad_along_width - pad_left __a : List[str] = pad_along_height // 2 __a : Union[str, Any] = pad_along_height - pad_top __a : str = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'constant' , 0.0 ) class __UpperCamelCase ( nn.Module ): def __init__( self , __a , __a , __a , __a , __a = 1 , __a = 1 , __a = False , __a = True , __a = True , ): '''simple docstring''' super().__init__() __a : Optional[int] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) __a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) __a : Union[str, Any] = nn.Convad( in_channels=__a , out_channels=__a , kernel_size=__a , stride=__a , padding=__a , groups=__a , bias=__a , padding_mode='zeros' , ) if use_normalization: __a : List[str] = nn.BatchNormad( num_features=__a , eps=config.layer_norm_eps , momentum=0.9997 , affine=__a , track_running_stats=__a , ) else: __a : Tuple = None if use_activation: if isinstance(__a , __a ): __a : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , __a ): __a : Union[str, Any] = ACTaFN[config.hidden_act] else: __a : Dict = config.hidden_act else: __a : List[Any] = None def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.config.tf_padding: __a : Union[str, Any] = apply_tf_padding(__a , self.convolution ) __a : Union[str, Any] = self.convolution(__a ) if self.normalization is not None: __a : str = self.normalization(__a ) if self.activation is not None: __a : Optional[int] = self.activation(__a ) return features class __UpperCamelCase ( lowerCAmelCase_ ): A_ = MobileNetVaConfig A_ = load_tf_weights_in_mobilenet_va A_ = "mobilenet_v1" A_ = "pixel_values" A_ = False def __UpperCAmelCase ( self , __a ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __lowercase : Any = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowercase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a = True ): '''simple docstring''' super().__init__(__a ) __a : Optional[int] = config __a : str = 32 __a : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) __a : Union[str, Any] = MobileNetVaConvLayer( __a , in_channels=config.num_channels , out_channels=__a , kernel_size=3 , stride=2 , ) __a : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __a : Any = nn.ModuleList() for i in range(13 ): __a : Union[str, Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 __a : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=3 , stride=strides[i] , groups=__a , ) ) self.layer.append( MobileNetVaConvLayer( __a , in_channels=__a , out_channels=__a , kernel_size=1 , ) ) __a : Optional[int] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __UpperCAmelCase ( self , __a ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a : int = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __a : Union[str, Any] = self.conv_stem(__a ) __a : Any = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): __a : List[str] = layer_module(__a ) if output_hidden_states: __a : List[Any] = all_hidden_states + (hidden_states,) __a : str = hidden_states if self.pooler is not None: __a : Union[str, Any] = torch.flatten(self.pooler(__a ) , start_dim=1 ) else: __a : int = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__a , pooler_output=__a , hidden_states=__a , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase_ , ) class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a ): '''simple docstring''' super().__init__(__a ) __a : Tuple = config.num_labels __a : Tuple = MobileNetVaModel(__a ) __a : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __a : Any = nn.Dropout(config.classifier_dropout_prob , inplace=__a ) __a : Any = nn.Linear(__a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCAmelCase ( self , __a = None , __a = None , __a = None , __a = None , ): '''simple docstring''' __a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __a : Dict = self.mobilenet_va(__a , output_hidden_states=__a , return_dict=__a ) __a : List[str] = outputs.pooler_output if return_dict else outputs[1] __a : int = self.classifier(self.dropout(__a ) ) __a : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a : int = 'single_label_classification' else: __a : Optional[Any] = 'multi_label_classification' if self.config.problem_type == "regression": __a : Optional[Any] = MSELoss() if self.num_labels == 1: __a : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __a : List[str] = CrossEntropyLoss() __a : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a : Tuple = BCEWithLogitsLoss() __a : Optional[int] = loss_fct(__a , __a ) if not return_dict: __a : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=__a , logits=__a , hidden_states=outputs.hidden_states , )
294
0
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
355
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase : str = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "dhaka" , _SCREAMING_SNAKE_CASE : int = 5 ): __a : Optional[Any] = min(_SCREAMING_SNAKE_CASE , 50 ) # Prevent abuse! __a : Optional[Any] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } __a : Tuple = requests.get('https://www.google.com/search' , params=_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ) __a : Dict = BeautifulSoup(html.text , 'html.parser' ) __a : List[str] = ''.join( re.findall(r'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) __a : Optional[Any] = json.dumps(_SCREAMING_SNAKE_CASE ) __a : List[str] = json.loads(_SCREAMING_SNAKE_CASE ) __a : List[Any] = re.findall( r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , _SCREAMING_SNAKE_CASE , ) if not matched_google_image_data: return 0 __a : Tuple = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(_SCREAMING_SNAKE_CASE ) , ) __a : Optional[Any] = re.findall( r'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , _SCREAMING_SNAKE_CASE , ) for index, fixed_full_res_image in enumerate(_SCREAMING_SNAKE_CASE ): if index >= max_images: return index __a : List[str] = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Tuple = bytes(_SCREAMING_SNAKE_CASE , 'ascii' ).decode( 'unicode-escape' ) __a : Dict = urllib.request.build_opener() __a : Union[str, Any] = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(_SCREAMING_SNAKE_CASE ) __a : List[Any] = F"""query_{query.replace(" " , "_" )}""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): os.makedirs(_SCREAMING_SNAKE_CASE ) urllib.request.urlretrieve( # noqa: S310 _SCREAMING_SNAKE_CASE , F"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: __lowercase : Optional[int] = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print('Please provide a search term.') raise
294
0
'''simple docstring''' from graphs.minimum_spanning_tree_kruskal import kruskal def lowerCamelCase (): __a : str = 9 __a : List[str] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __a : Tuple = kruskal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Tuple = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(_SCREAMING_SNAKE_CASE ) == sorted(_SCREAMING_SNAKE_CASE )
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split(',' ) names.sort() __a : Union[str, Any] = 0 __a : Tuple = 0 for i, name in enumerate(_SCREAMING_SNAKE_CASE ): for letter in name: name_score += ord(_SCREAMING_SNAKE_CASE ) - 64 total_score += (i + 1) * name_score __a : Any = 0 return total_score if __name__ == "__main__": print(solution())
294
0
'''simple docstring''' import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint __lowercase : Any = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } __lowercase : Union[str, Any] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): __a : List[str] = list(state_dict.keys() ) for name in state_dict_keys: __a : Optional[Any] = state_dict.pop(_SCREAMING_SNAKE_CASE ) # emb -> embedding if name.startswith('emb.' ): __a : int = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): __a : Dict = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention __a : Optional[int] = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , _SCREAMING_SNAKE_CASE ) # ffn -> feed_forward __a : Tuple = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , _SCREAMING_SNAKE_CASE ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): __a : str = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): __a : List[Any] = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): __a : Any = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": __a : int = 'rwkv.' + name __a : Optional[int] = weight return state_dict def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Any=None , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : Tuple=False , _SCREAMING_SNAKE_CASE : List[Any]=None ): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) __a : Union[str, Any] = 50_277 __a : Optional[Any] = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: __a : Optional[Any] = PreTrainedTokenizerFast(tokenizer_file=_SCREAMING_SNAKE_CASE ) __a : int = len(_SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) # 2. Build the config __a : Any = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: __a : int = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.' ) if size not in possible_sizes: raise ValueError(F"""`size` should be one of {possible_sizes}, got {size}.""" ) __a : Optional[int] = RwkvConfig( vocab_size=_SCREAMING_SNAKE_CASE , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_SCREAMING_SNAKE_CASE ) # 3. Download model file then convert state_dict __a : List[str] = hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' ) __a : Any = convert_state_dict(_SCREAMING_SNAKE_CASE ) # 4. Split in shards and save __a : Any = shard_checkpoint(_SCREAMING_SNAKE_CASE ) for shard_file, shard in shards.items(): torch.save(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) if index is not None: __a : int = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save the index as well with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: __a : Union[str, Any] = json.dumps(_SCREAMING_SNAKE_CASE , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE ) + '\n' f.write(_SCREAMING_SNAKE_CASE ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.' ) __a : Dict = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: __a : int = torch.load(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.' ) __a : Optional[int] = AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE ) model.push_to_hub(_SCREAMING_SNAKE_CASE , max_shard_size='2GB' ) tokenizer.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) __lowercase : Union[str, Any] = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
357
'''simple docstring''' __lowercase : Optional[Any] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} __lowercase : List[str] = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] ): __a : Any = start # add current to visited visited.append(_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : Dict = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(_SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: __a : List[Any] = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": __lowercase : Union[str, Any] = topological_sort('a', [], []) print(sort)
294
0
'''simple docstring''' import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class __UpperCamelCase : def __init__( self , __a , __a=None , __a=None , __a=None , __a="resnet50" , __a=3 , __a=32 , __a=3 , __a=True , __a=True , ): '''simple docstring''' __a : List[Any] = parent __a : Dict = out_indices if out_indices is not None else [4] __a : str = stage_names __a : int = out_features __a : List[str] = backbone __a : List[Any] = batch_size __a : Tuple = image_size __a : Dict = num_channels __a : int = use_pretrained_backbone __a : int = is_training def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Any = self.get_config() return config, pixel_values def __UpperCAmelCase ( self ): '''simple docstring''' return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : List[Any] = TimmBackbone(config=__a ) model.to(__a ) model.eval() with torch.no_grad(): __a : int = model(__a ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.prepare_config_and_inputs() __a : int = config_and_inputs __a : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch @require_timm class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TimmBackbone,) if is_torch_available() else () A_ = {"feature-extraction": TimmBackbone} if is_torch_available() else {} A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = TimmBackboneModelTester(self ) __a : Any = ConfigTester(self , config_class=__a , has_text_modality=__a ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = 'resnet18' __a : str = 'microsoft/resnet-18' __a : Union[str, Any] = AutoBackbone.from_pretrained(__a , use_timm_backbone=__a ) __a : str = AutoBackbone.from_pretrained(__a ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) __a : Optional[int] = AutoBackbone.from_pretrained(__a , use_timm_backbone=__a , out_indices=[1, 2, 3] ) __a : str = AutoBackbone.from_pretrained(__a , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip('TimmBackbone doesn\'t support feed forward chunking' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone initialization is managed on the timm side' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('TimmBackbone doesn\'t support output_attentions.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('Safetensors is not supported by timm.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Optional[int] = model_class(__a ) __a : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __a : Optional[Any] = True __a : Optional[Any] = self.has_attentions # no need to test all models as different heads yield the same functionality __a : Tuple = self.all_model_classes[0] __a : int = model_class(__a ) model.to(__a ) __a : int = self._prepare_for_class(__a , __a ) __a : Any = model(**__a ) __a : Tuple = outputs[0][-1] # Encoder-/Decoder-only models __a : List[str] = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: __a : Union[str, Any] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=__a ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : int = model_class(__a ) model.to(__a ) model.eval() __a : List[str] = model(**__a ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None __a : Dict = copy.deepcopy(__a ) __a : Tuple = None __a : Any = model_class(__a ) model.to(__a ) model.eval() __a : List[str] = model(**__a ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights __a : Union[str, Any] = copy.deepcopy(__a ) __a : Union[str, Any] = False __a : Any = model_class(__a ) model.to(__a ) model.eval() __a : Union[str, Any] = model(**__a )
358
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=3 , __a=True , __a=True , __a=0.1 , __a=0.1 , __a=224 , __a=1000 , __a=[3, 3, 6, 4] , __a=[48, 56, 112, 220] , ): '''simple docstring''' __a : Optional[int] = parent __a : Dict = batch_size __a : Dict = num_channels __a : str = is_training __a : Optional[int] = use_labels __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[Any] = num_labels __a : Tuple = image_size __a : Optional[Any] = layer_depths __a : Dict = embed_dims def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : int = None if self.use_labels: __a : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) __a : List[str] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='gelu' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=__a , layer_scale_init_value=1E-5 , ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : int = SwiftFormerModel(config=__a ) model.to(__a ) model.eval() __a : Optional[Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def __UpperCAmelCase ( self , __a , __a , __a ): '''simple docstring''' __a : Tuple = self.num_labels __a : Optional[int] = SwiftFormerForImageClassification(__a ) model.to(__a ) model.eval() __a : int = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) __a : int = SwiftFormerForImageClassification(__a ) model.to(__a ) model.eval() __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' (__a) : Tuple = self.prepare_config_and_inputs() __a : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () A_ = ( {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = SwiftFormerModelTester(self ) __a : Dict = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='SwiftFormer does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Optional[Any] = model_class(__a ) __a : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[Any] = model_class(__a ) __a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[int] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : int = SwiftFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip(reason='SwiftFormer does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : Optional[Any] = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Tuple = 8 self.assertEqual(len(__a ) , __a ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(__a ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Any = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Union[str, Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def _config_zero_init(__a ): __a : List[Any] = copy.deepcopy(__a ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(__a , __a , 1E-1_0 ) if isinstance(getattr(__a , __a , __a ) , __a ): __a : List[Any] = _config_zero_init(getattr(__a , __a ) ) setattr(__a , __a , __a ) return configs_no_init __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() __a : Optional[Any] = _config_zero_init(__a ) for model_class in self.all_model_classes: __a : Tuple = model_class(config=__a ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def lowerCamelCase (): __a : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs' ).to(__a ) __a : Optional[Any] = self.default_image_processor __a : Tuple = prepare_img() __a : int = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): __a : Optional[Any] = model(**__a ) # verify the logits __a : Tuple = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : int = torch.tensor([[-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0]] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) )
359
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : str = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Tuple = SwinConfig(image_size=192 ) if "base" in model_name: __a : Optional[int] = 6 __a : Optional[Any] = 128 __a : Union[str, Any] = (2, 2, 18, 2) __a : Tuple = (4, 8, 16, 32) elif "large" in model_name: __a : List[Any] = 12 __a : str = 192 __a : List[str] = (2, 2, 18, 2) __a : Optional[int] = (6, 12, 24, 48) else: raise ValueError('Model not supported, only supports base and large variants' ) __a : Tuple = window_size __a : Optional[int] = embed_dim __a : str = depths __a : Dict = num_heads return config def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple ): if "encoder.mask_token" in name: __a : List[Any] = name.replace('encoder.mask_token' , 'embeddings.mask_token' ) if "encoder.patch_embed.proj" in name: __a : int = name.replace('encoder.patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "encoder.patch_embed.norm" in name: __a : List[str] = name.replace('encoder.patch_embed.norm' , 'embeddings.norm' ) if "attn.proj" in name: __a : List[Any] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: __a : Union[str, Any] = name.replace('attn' , 'attention.self' ) if "norm1" in name: __a : Any = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: __a : Any = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: __a : Dict = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: __a : Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": __a : List[str] = 'layernorm.weight' if name == "encoder.norm.bias": __a : Optional[Any] = 'layernorm.bias' if "decoder" in name: pass else: __a : Optional[Any] = 'swin.' + name return name def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[Any] ): for key in orig_state_dict.copy().keys(): __a : int = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "attn_mask" in key: pass elif "qkv" in key: __a : List[str] = key.split('.' ) __a : str = int(key_split[2] ) __a : List[str] = int(key_split[4] ) __a : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __a : List[Any] = val[:dim, :] __a : Optional[int] = val[ dim : dim * 2, : ] __a : Dict = val[-dim:, :] else: __a : int = val[ :dim ] __a : Optional[Any] = val[ dim : dim * 2 ] __a : List[Any] = val[ -dim: ] else: __a : Any = val return orig_state_dict def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ): __a : int = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )['model'] __a : Any = get_swin_config(_SCREAMING_SNAKE_CASE ) __a : List[str] = SwinForMaskedImageModeling(_SCREAMING_SNAKE_CASE ) model.eval() __a : List[Any] = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) __a : Dict = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Any = ViTImageProcessor(size={'height': 192, 'width': 192} ) __a : Optional[int] = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) __a : List[str] = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) with torch.no_grad(): __a : Optional[Any] = model(**_SCREAMING_SNAKE_CASE ).logits print(outputs.keys() ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print(F"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(F"""microsoft/{model_name}""" ) image_processor.push_to_hub(F"""microsoft/{model_name}""" ) if __name__ == "__main__": __lowercase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='swin-base-simmim-window6-192', type=str, choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'], help='Name of the Swin SimMIM model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth', type=str, help='Path to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __lowercase : Tuple = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
360
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __UpperCamelCase ( unittest.TestCase ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = 'laion/clap-htsat-unfused' __a : Optional[Any] = tempfile.mkdtemp() def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self , **__a ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def __UpperCAmelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = self.get_tokenizer() __a : List[str] = self.get_feature_extractor() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) __a : Tuple = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __a : List[str] = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) __a : Tuple = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : int = self.get_tokenizer() __a : str = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : int = floats_list((3, 1000) ) __a : str = feature_extractor(__a , return_tensors='np' ) __a : int = processor(audios=__a , 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 __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.get_feature_extractor() __a : Any = self.get_tokenizer() __a : Any = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Union[str, Any] = 'This is a test string' __a : Union[str, Any] = processor(text=__a ) __a : Tuple = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.get_feature_extractor() __a : str = self.get_tokenizer() __a : List[str] = ClapProcessor(tokenizer=__a , feature_extractor=__a ) __a : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a : Optional[int] = processor.batch_decode(__a ) __a : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.get_feature_extractor() __a : Optional[int] = self.get_tokenizer() __a : int = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
294
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Optional[int] = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any = [ 'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'GraphormerForGraphClassification', 'GraphormerModel', 'GraphormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys __lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
361
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase ( lowerCAmelCase_ ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : Union[str, Any] = batch_size __a : Optional[int] = seq_length __a : List[str] = is_training __a : Any = use_input_mask __a : Optional[int] = use_token_type_ids __a : Any = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : List[str] = num_hidden_layers __a : str = num_attention_heads __a : Optional[int] = intermediate_size __a : Tuple = hidden_act __a : Union[str, Any] = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Optional[int] = max_position_embeddings __a : Dict = type_vocab_size __a : Any = type_sequence_label_size __a : Dict = initializer_range __a : Optional[Any] = num_labels __a : Optional[Any] = num_choices __a : Union[str, Any] = relative_attention __a : List[str] = position_biased_input __a : List[Any] = pos_att_type __a : Tuple = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[Any] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Any = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Optional[int] = None __a : int = None __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Dict = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __a : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a )[0] __a : str = model(__a , token_type_ids=__a )[0] __a : Optional[int] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : int = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __a : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : List[Any] = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __a : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __a : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __a : str = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __a : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Dict = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) A_ = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) A_ = True A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = DebertaVaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __a : Optional[Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : int = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __a : str = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
294
0
'''simple docstring''' import sys __lowercase : Union[str, Any] = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : List[str] = 1 for digit in s: product *= int(_SCREAMING_SNAKE_CASE ) return product def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = N ): __a : Optional[int] = -sys.maxsize - 1 __a : Optional[Any] = n[:13] __a : int = 13 while cur_index < len(_SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): __a : List[Any] = substr[1:] + n[cur_index] cur_index += 1 else: __a : Dict = max(_SCREAMING_SNAKE_CASE , str_eval(_SCREAMING_SNAKE_CASE ) ) __a : Optional[Any] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
362
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): if is_torch_version('<' , '2.0.0' ) or not hasattr(_SCREAMING_SNAKE_CASE , '_dynamo' ): return False return isinstance(_SCREAMING_SNAKE_CASE , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : bool = True ): __a : int = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a : Any = is_compiled_module(_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[Any] = model __a : Union[str, Any] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = model.module if not keep_fpaa_wrapper: __a : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , 'forward' ) __a : str = model.__dict__.pop('_original_forward' , _SCREAMING_SNAKE_CASE ) if original_forward is not None: while hasattr(_SCREAMING_SNAKE_CASE , '__wrapped__' ): __a : Any = forward.__wrapped__ if forward == original_forward: break __a : str = forward if getattr(_SCREAMING_SNAKE_CASE , '_converted_to_transformer_engine' , _SCREAMING_SNAKE_CASE ): convert_model(_SCREAMING_SNAKE_CASE , to_transformer_engine=_SCREAMING_SNAKE_CASE ) if is_compiled: __a : List[str] = model __a : Optional[int] = compiled_model return model def lowerCamelCase (): PartialState().wait_for_everyone() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif PartialState().local_process_index == 0: torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @contextmanager def lowerCamelCase (**_SCREAMING_SNAKE_CASE : Tuple ): for key, value in kwargs.items(): __a : Optional[int] = str(_SCREAMING_SNAKE_CASE ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): if not hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ) and not hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): __a : List[Any] = getattr(_SCREAMING_SNAKE_CASE , '__class__' , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '__qualname__' ): return obj.__qualname__ if hasattr(_SCREAMING_SNAKE_CASE , '__name__' ): return obj.__name__ return str(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ): for key, value in source.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : int = destination.setdefault(_SCREAMING_SNAKE_CASE , {} ) merge_dicts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __a : Tuple = value return destination def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = None ): if port is None: __a : List[str] = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
294
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __lowercase : Dict = logging.get_logger(__name__) __lowercase : Tuple = { 'post_extract_proj': 'feature_projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.upsample.0': 'encoder.upsample.projection', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'layer_norm', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): for attribute in key.split('.' ): __a : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a : Any = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a : int = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Union[str, Any] = value elif weight_type == "weight_g": __a : str = value elif weight_type == "weight_v": __a : Any = value elif weight_type == "bias": __a : int = value else: __a : Optional[int] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int ): __a : Dict = [] __a : Any = fairseq_model.state_dict() __a : Union[str, Any] = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): __a : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) __a : List[str] = True else: for key, mapped_key in MAPPING.items(): __a : Optional[Any] = 'sew.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __a : Dict = True if "*" in mapped_key: __a : Tuple = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] __a : Optional[int] = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a : Union[str, Any] = 'weight_g' elif "weight_v" in name: __a : Dict = 'weight_v' elif "weight" in name: __a : Union[str, Any] = 'weight' elif "bias" in name: __a : Optional[int] = 'bias' else: __a : int = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): __a : Union[str, Any] = full_name.split('conv_layers.' )[-1] __a : Dict = name.split('.' ) __a : Optional[Any] = int(items[0] ) __a : Optional[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : List[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.""" ) __a : Optional[int] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __a : Dict = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : Optional[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int ): __a : Optional[Any] = SEWConfig() if is_finetuned: __a : Optional[int] = model.wav_encoder.wav_model.cfg else: __a : List[str] = model.cfg __a : Any = fs_config.conv_bias __a : Optional[Any] = eval(fs_config.conv_feature_layers ) __a : int = [x[0] for x in conv_layers] __a : str = [x[1] for x in conv_layers] __a : Optional[Any] = [x[2] for x in conv_layers] __a : Optional[int] = 'gelu' __a : List[Any] = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group' __a : Optional[Any] = 0.0 __a : List[Any] = fs_config.activation_fn.name __a : Any = fs_config.encoder_embed_dim __a : Tuple = 0.0_2 __a : Optional[Any] = fs_config.encoder_ffn_embed_dim __a : Tuple = 1e-5 __a : int = fs_config.encoder_layerdrop __a : List[str] = fs_config.encoder_attention_heads __a : Optional[int] = fs_config.conv_pos_groups __a : Optional[Any] = fs_config.conv_pos __a : List[Any] = len(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = fs_config.encoder_layers __a : Optional[Any] = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: __a : Tuple = model.cfg __a : List[Any] = fs_config.final_dropout __a : Any = fs_config.layerdrop __a : List[str] = fs_config.activation_dropout __a : List[str] = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 __a : Any = fs_config.attention_dropout __a : Any = fs_config.dropout_input __a : Tuple = fs_config.dropout __a : List[Any] = fs_config.mask_channel_length __a : Union[str, Any] = fs_config.mask_channel_prob __a : List[Any] = fs_config.mask_length __a : Dict = fs_config.mask_prob __a : str = 'Wav2Vec2FeatureExtractor' __a : Any = 'Wav2Vec2CTCTokenizer' return config @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str=None , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : str=True ): if is_finetuned: __a : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __a : str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: __a : Dict = SEWConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: __a : List[str] = convert_config(model[0] , _SCREAMING_SNAKE_CASE ) __a : int = model[0].eval() __a : List[str] = True if config.feat_extract_norm == 'layer' else False __a : Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) if is_finetuned: if dict_path: __a : Any = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __a : List[str] = target_dict.pad_index __a : Optional[Any] = target_dict.bos_index __a : Tuple = target_dict.pad_index __a : Dict = target_dict.bos_index __a : str = target_dict.eos_index __a : List[Any] = len(target_dict.symbols ) __a : Tuple = os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(target_dict.indices , _SCREAMING_SNAKE_CASE ) __a : Optional[int] = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , 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=_SCREAMING_SNAKE_CASE , ) __a : Optional[int] = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) __a : Any = SEWForCTC(_SCREAMING_SNAKE_CASE ) else: __a : str = SEWModel(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--is_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) __lowercase : str = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
363
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
294
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: __lowercase : Optional[int] = None __lowercase : Any = logging.get_logger(__name__) __lowercase : str = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __lowercase : List[Any] = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', }, 'tokenizer_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json', }, } __lowercase : List[Any] = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } __lowercase : str = '▁' # Segments (not really needed) __lowercase : Dict = 0 __lowercase : Optional[int] = 1 __lowercase : Any = 2 __lowercase : List[str] = 3 __lowercase : int = 4 class __UpperCamelCase ( lowerCAmelCase_ ): A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ = "left" A_ = XLNetTokenizer def __init__( self , __a=None , __a=None , __a=False , __a=True , __a=False , __a="<s>" , __a="</s>" , __a="<unk>" , __a="<sep>" , __a="<pad>" , __a="<cls>" , __a="<mask>" , __a=["<eop>", "<eod>"] , **__a , ): '''simple docstring''' __a : str = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token super().__init__( vocab_file=__a , tokenizer_file=__a , do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , additional_special_tokens=__a , **__a , ) __a : Any = 3 __a : Optional[int] = do_lower_case __a : Optional[int] = remove_space __a : Optional[Any] = keep_accents __a : Union[str, Any] = vocab_file __a : Tuple = False if not self.vocab_file else True def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : Dict = [self.sep_token_id] __a : Optional[int] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : List[str] = [self.sep_token_id] __a : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(__a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : Union[str, Any] = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ): copyfile(self.vocab_file , __a ) return (out_vocab_file,)
364
'''simple docstring''' from __future__ import annotations from dataclasses import dataclass @dataclass class __UpperCamelCase : A_ = 42 A_ = None A_ = None def lowerCamelCase (_SCREAMING_SNAKE_CASE : TreeNode | None ): # Validation def is_valid_tree(_SCREAMING_SNAKE_CASE : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_SCREAMING_SNAKE_CASE ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( _SCREAMING_SNAKE_CASE : TreeNode | None , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _SCREAMING_SNAKE_CASE , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _SCREAMING_SNAKE_CASE ) ) return is_binary_search_tree_recursive_check(_SCREAMING_SNAKE_CASE , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ) -> Optional[int]: __a : Optional[int] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
365
'''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. __lowercase : Dict = 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 (_SCREAMING_SNAKE_CASE : Optional[Any] ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): from transformers.testing_utils import pytest_terminal_summary_main __a : Any = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE , id=_SCREAMING_SNAKE_CASE )
294
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Any = logging.get_logger(__name__) __lowercase : str = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "sew-d" def __init__( self , __a=32 , __a=768 , __a=12 , __a=12 , __a=3072 , __a=2 , __a=512 , __a=256 , __a=True , __a=True , __a=("p2c", "c2p") , __a="layer_norm" , __a="gelu_python" , __a=0.1 , __a=0.1 , __a=0.1 , __a=0.0 , __a=0.1 , __a=0.02 , __a=1E-7 , __a=1E-5 , __a="group" , __a="gelu" , __a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __a=False , __a=128 , __a=16 , __a=True , __a=0.05 , __a=10 , __a=2 , __a=0.0 , __a=10 , __a=0 , __a="mean" , __a=False , __a=False , __a=256 , __a=0 , __a=1 , __a=2 , **__a , ): '''simple docstring''' super().__init__(**__a , pad_token_id=__a , bos_token_id=__a , eos_token_id=__a ) __a : Any = hidden_size __a : List[str] = feat_extract_norm __a : List[Any] = feat_extract_activation __a : Tuple = list(__a ) __a : Union[str, Any] = list(__a ) __a : List[Any] = list(__a ) __a : Dict = conv_bias __a : str = num_conv_pos_embeddings __a : Optional[Any] = num_conv_pos_embedding_groups __a : List[str] = len(self.conv_dim ) __a : str = num_hidden_layers __a : Any = intermediate_size __a : int = squeeze_factor __a : str = max_position_embeddings __a : int = position_buckets __a : Any = share_att_key __a : Dict = relative_attention __a : List[Any] = norm_rel_ebd __a : str = list(__a ) __a : Any = hidden_act __a : List[Any] = num_attention_heads __a : Dict = hidden_dropout __a : Optional[Any] = attention_dropout __a : List[str] = activation_dropout __a : Any = feat_proj_dropout __a : Dict = final_dropout __a : int = layer_norm_eps __a : Optional[Any] = feature_layer_norm_eps __a : Optional[int] = initializer_range __a : Optional[Any] = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f"""but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a : List[Any] = apply_spec_augment __a : int = mask_time_prob __a : int = mask_time_length __a : str = mask_time_min_masks __a : List[str] = mask_feature_prob __a : Optional[int] = mask_feature_length __a : Optional[int] = mask_feature_min_masks # ctc loss __a : Optional[Any] = ctc_loss_reduction __a : int = ctc_zero_infinity # sequence classification __a : int = use_weighted_layer_sum __a : Any = classifier_proj_size @property def __UpperCAmelCase ( self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
366
'''simple docstring''' import re from filelock import FileLock try: import nltk __lowercase : Optional[Any] = True except (ImportError, ModuleNotFoundError): __lowercase : Dict = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): re.sub('<n>' , '' , _SCREAMING_SNAKE_CASE ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_SCREAMING_SNAKE_CASE ) )
294
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): while b: __a : Tuple = b, a % b return a def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): return a if b == 0 else euclidean_gcd_recursive(_SCREAMING_SNAKE_CASE , a % b ) def lowerCamelCase (): print(F"""euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}""" ) print(F"""euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}""" ) print(F"""euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}""" ) print(F"""euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}""" ) print(F"""euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}""" ) print(F"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}""" ) print(F"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}""" ) print(F"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}""" ) if __name__ == "__main__": main()
367
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowercase : int = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowercase : Any = [0, 25, 50] __lowercase : int = [25, 50, 75] __lowercase : List[str] = fuzz.membership.trimf(X, abca) __lowercase : Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowercase : List[Any] = np.ones(75) __lowercase : Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowercase : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowercase : str = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowercase : List[Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowercase : Optional[Any] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowercase : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowercase : Optional[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowercase : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
294
0