code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =None _lowerCamelCase =None a__ : str = namedtuple('CoinsDistribResult', 'moves excess') def __snake_case ( SCREAMING_SNAKE_CASE_ : TreeNode | None ) -> int: """simple docstring""" if root is None: return 0 # Validation def count_nodes(SCREAMING_SNAKE_CASE_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(SCREAMING_SNAKE_CASE_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(SCREAMING_SNAKE_CASE_ ) != count_coins(SCREAMING_SNAKE_CASE_ ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(SCREAMING_SNAKE_CASE_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase, UpperCAmelCase = get_distrib(node.left ) UpperCAmelCase, UpperCAmelCase = get_distrib(node.right ) UpperCAmelCase = 1 - left_distrib_excess UpperCAmelCase = 1 - right_distrib_excess UpperCAmelCase = ( left_distrib_moves + right_distrib_moves + abs(SCREAMING_SNAKE_CASE_ ) + abs(SCREAMING_SNAKE_CASE_ ) ) UpperCAmelCase = node.data - coins_to_left - coins_to_right return CoinsDistribResult(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return get_distrib(SCREAMING_SNAKE_CASE_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a__ : List[Any] = logging.get_logger(__name__) a__ : int = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a__ : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] a__ : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="whisper" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[Any] , a__ : Any=51865 , a__ : Any=80 , a__ : Dict=6 , a__ : int=4 , a__ : int=6 , a__ : str=4 , a__ : int=1536 , a__ : Optional[Any]=1536 , a__ : str=0.0 , a__ : Optional[int]=0.0 , a__ : Optional[int]=50257 , a__ : int=True , a__ : Optional[int]=True , a__ : str="gelu" , a__ : List[str]=256 , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Any=0.0 , a__ : str=0.02 , a__ : str=False , a__ : int=1500 , a__ : Tuple=448 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Tuple=None , a__ : List[Any]=[220, 50256] , a__ : Optional[int]=False , a__ : Optional[Any]=256 , a__ : Any=False , a__ : int=0.05 , a__ : Optional[Any]=10 , a__ : Dict=2 , a__ : Optional[Any]=0.0 , a__ : Tuple=10 , a__ : Any=0 , a__ : str=7 , **a__ : Any , ): UpperCAmelCase = vocab_size UpperCAmelCase = num_mel_bins UpperCAmelCase = d_model UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size UpperCAmelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks UpperCAmelCase = median_filter_width super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , suppress_tokens=a__ , begin_suppress_tokens=a__ , **a__ , ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : List[str] ): UpperCAmelCase = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: UpperCAmelCase = {0: '''batch'''} else: UpperCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs def __snake_case ( self : str , a__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a__ : int = -1 , a__ : int = -1 , a__ : bool = False , a__ : Optional["TensorType"] = None , a__ : int = 22050 , a__ : float = 5.0 , a__ : int = 220 , ): UpperCAmelCase = OrderedDict() UpperCAmelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a__ , framework=a__ , sampling_rate=a__ , time_duration=a__ , frequency=a__ , ) UpperCAmelCase = encoder_inputs['''input_features'''].shape[2] UpperCAmelCase = encoder_sequence_length // 2 if self.use_past else seq_length UpperCAmelCase = super().generate_dummy_inputs( preprocessor.tokenizer , a__ , a__ , a__ , a__ ) UpperCAmelCase = encoder_inputs.pop('''input_features''' ) UpperCAmelCase = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: UpperCAmelCase = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __snake_case ( self : Dict ): return 1e-3
51
1
'''simple docstring''' from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __snake_case ( SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" UpperCAmelCase = prime_factors(SCREAMING_SNAKE_CASE_ ) if is_square_free(SCREAMING_SNAKE_CASE_ ): return -1 if len(SCREAMING_SNAKE_CASE_ ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =LEDConfig _lowerCamelCase ={} _lowerCamelCase ="gelu" def __init__( self : Tuple , a__ : Any , a__ : int=13 , a__ : List[Any]=7 , a__ : int=True , a__ : Union[str, Any]=False , a__ : Tuple=99 , a__ : Any=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : List[Any]=37 , a__ : List[Any]=0.1 , a__ : Any=0.1 , a__ : Optional[int]=20 , a__ : List[Any]=2 , a__ : Union[str, Any]=1 , a__ : List[Any]=0 , a__ : Union[str, Any]=4 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after UpperCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests UpperCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) UpperCAmelCase = prepare_led_inputs_dict(a__ , a__ , a__ ) UpperCAmelCase = tf.concat( [tf.zeros_like(a__ )[:, :-1], tf.ones_like(a__ )[:, -1:]] , axis=-1 , ) UpperCAmelCase = global_attention_mask return config, inputs_dict def __snake_case ( self : Optional[int] , a__ : List[str] , a__ : int ): UpperCAmelCase = TFLEDModel(config=a__ ).get_decoder() UpperCAmelCase = inputs_dict['''input_ids'''] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(a__ , attention_mask=a__ , use_cache=a__ ) UpperCAmelCase, UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(a__ , attention_mask=a__ )[0] UpperCAmelCase = model(a__ , attention_mask=a__ , past_key_values=a__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(a__ , a__ , rtol=1e-3 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=None , ) -> Dict: """simple docstring""" if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowerCamelCase =(TFLEDForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase =( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : Optional[Any] ): UpperCAmelCase = TFLEDModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ ) def __snake_case ( self : int ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = tf.zeros_like(inputs_dict['''attention_mask'''] ) UpperCAmelCase = 2 UpperCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) UpperCAmelCase = True UpperCAmelCase = self.model_tester.seq_length UpperCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(a__ : Tuple ): UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(a__ : int ): UpperCAmelCase = [t.numpy() for t in outputs.encoder_attentions] UpperCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = len(a__ ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) if self.is_encoder_decoder: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_decoder_attentions_output(a__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) ) self.assertEqual(model.config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __snake_case ( self : Any ): pass def __snake_case ( self : Union[str, Any] ): # TODO: Head-masking not yet implement pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> Tuple: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE_ , dtype=tf.intaa ) a__ : int = 1e-4 @slow @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, 768) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 ) def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 , rtol=1e-3 )
51
1
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =RoCBertTokenizer _lowerCamelCase =None _lowerCamelCase =False _lowerCamelCase =True _lowerCamelCase =filter_non_english def __snake_case ( self : Any ): super().setUp() UpperCAmelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''你''', '''好''', '''是''', '''谁''', '''a''', '''b''', '''c''', '''d'''] UpperCAmelCase = {} UpperCAmelCase = {} for i, value in enumerate(a__ ): UpperCAmelCase = i UpperCAmelCase = i UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_shape_file'''] ) UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_pronunciation_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.word_shape_file , '''w''' , encoding='''utf-8''' ) as word_shape_writer: json.dump(a__ , a__ , ensure_ascii=a__ ) with open(self.word_pronunciation_file , '''w''' , encoding='''utf-8''' ) as word_pronunciation_writer: json.dump(a__ , a__ , ensure_ascii=a__ ) def __snake_case ( self : List[Any] ): UpperCAmelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCAmelCase = tokenizer.tokenize('''你好[SEP]你是谁''' ) self.assertListEqual(a__ , ['''你''', '''好''', '''[SEP]''', '''你''', '''是''', '''谁'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(a__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(a__ ) , [5, 6, 2, 5, 7, 8] ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = RoCBertBasicTokenizer(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 __snake_case ( self : Tuple ): UpperCAmelCase = RoCBertBasicTokenizer(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 __snake_case ( self : Optional[int] ): UpperCAmelCase = RoCBertBasicTokenizer(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 __snake_case ( self : Tuple ): UpperCAmelCase = RoCBertBasicTokenizer(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 __snake_case ( self : int ): UpperCAmelCase = RoCBertBasicTokenizer(do_lower_case=a__ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = RoCBertBasicTokenizer(do_lower_case=a__ , strip_accents=a__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = RoCBertBasicTokenizer(do_lower_case=a__ , strip_accents=a__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = RoCBertBasicTokenizer(do_lower_case=a__ , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] UpperCAmelCase = {} for i, token in enumerate(a__ ): UpperCAmelCase = i UpperCAmelCase = RoCBertWordpieceTokenizer(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 __snake_case ( self : int ): 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 __snake_case ( self : Union[str, Any] ): 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 __snake_case ( self : Any ): 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 __snake_case ( self : Optional[int] ): UpperCAmelCase = self.get_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]''']] ) if self.test_rust_tokenizer: UpperCAmelCase = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(a__ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) def __snake_case ( self : int ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) UpperCAmelCase = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." UpperCAmelCase = tokenizer_r.encode_plus( a__ , return_attention_mask=a__ , return_token_type_ids=a__ , return_offsets_mapping=a__ , add_special_tokens=a__ , ) UpperCAmelCase = tokenizer_r.do_lower_case if hasattr(a__ , '''do_lower_case''' ) else False UpperCAmelCase = ( [ ((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 __snake_case ( self : List[str] ): UpperCAmelCase = ['''的''', '''人''', '''有'''] UpperCAmelCase = ''''''.join(a__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase = True UpperCAmelCase = self.tokenizer_class.from_pretrained(a__ , **a__ ) UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) UpperCAmelCase = tokenizer_p.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = tokenizer_r.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(a__ ) UpperCAmelCase = 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__ ) UpperCAmelCase = False UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) UpperCAmelCase = self.tokenizer_class.from_pretrained(a__ , **a__ ) UpperCAmelCase = tokenizer_r.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = tokenizer_p.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(a__ ) UpperCAmelCase = tokenizer_p.convert_ids_to_tokens(a__ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCAmelCase = [ f"##{token}" if idx != 0 else token for idx, token in enumerate(a__ ) ] self.assertListEqual(a__ , a__ ) self.assertListEqual(a__ , a__ ) @slow def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCAmelCase = tokenizer.encode('''你好''' , add_special_tokens=a__ ) UpperCAmelCase = tokenizer.encode('''你是谁''' , add_special_tokens=a__ ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(a__ ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(a__ , a__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __snake_case ( self : str ): UpperCAmelCase = self.get_tokenizers(do_lower_case=a__ ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): UpperCAmelCase = '''你好,你是谁''' UpperCAmelCase = tokenizer.tokenize(a__ ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ ) UpperCAmelCase = tokenizer.convert_tokens_to_shape_ids(a__ ) UpperCAmelCase = tokenizer.convert_tokens_to_pronunciation_ids(a__ ) UpperCAmelCase = tokenizer.prepare_for_model( a__ , a__ , a__ , add_special_tokens=a__ ) UpperCAmelCase = tokenizer.encode_plus(a__ , add_special_tokens=a__ ) self.assertEqual(a__ , a__ )
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : List[Any] = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available a__ : Optional[Any] = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = ['HerbertTokenizerFast'] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys a__ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : Union[str, Any] , a__ : List[str]=None , a__ : Union[str, Any]=None , **a__ : Optional[Any] ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Any , a__ : Any=None , a__ : str=None , a__ : List[Any]=None , **a__ : List[str] ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : Optional[Any] , *a__ : int , **a__ : List[Any] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : Any , *a__ : Union[str, Any] , **a__ : Any ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
51
1
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , *a__ : List[Any] , a__ : Tuple=None , a__ : List[str]=None , **a__ : Any ): super().__init__(*a__ , **a__ ) UpperCAmelCase = eval_examples UpperCAmelCase = post_process_function def __snake_case ( self : Any , a__ : Any=None , a__ : Optional[Any]=None , a__ : Dict=None , a__ : str = "eval" ): UpperCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset UpperCAmelCase = self.get_eval_dataloader(a__ ) UpperCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( a__ , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a__ , metric_key_prefix=a__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( a__ , a__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default UpperCAmelCase = self.post_process_function(a__ , a__ , output.predictions ) UpperCAmelCase = self.compute_metrics(a__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): UpperCAmelCase = metrics.pop(a__ ) metrics.update(output.metrics ) else: UpperCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(a__ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) UpperCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , a__ ) return metrics def __snake_case ( self : str , a__ : Optional[int] , a__ : List[Any] , a__ : List[str]=None , a__ : str = "test" ): UpperCAmelCase = self.get_test_dataloader(a__ ) # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( a__ , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a__ , metric_key_prefix=a__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( a__ , a__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output UpperCAmelCase = self.post_process_function(a__ , a__ , output.predictions , '''predict''' ) UpperCAmelCase = self.compute_metrics(a__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): UpperCAmelCase = metrics.pop(a__ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a__ )
51
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
1
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Tuple ): UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = 5 # Realm tok UpperCAmelCase = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCAmelCase = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(a__ , exist_ok=a__ ) UpperCAmelCase = os.path.join(a__ , 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] ) ) UpperCAmelCase = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(a__ , exist_ok=a__ ) def __snake_case ( self : List[Any] ): return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def __snake_case ( self : List[Any] ): shutil.rmtree(self.tmpdirname ) def __snake_case ( self : List[Any] ): UpperCAmelCase = RealmConfig(num_block_records=self.num_block_records ) return config def __snake_case ( self : int ): UpperCAmelCase = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = np.array( [ B'''This is the first record''', B'''This is the second record''', B'''This is the third record''', B'''This is the fourth record''', B'''This is the fifth record''', B'''This is a longer longer longer record''', ] , dtype=a__ , ) return block_records def __snake_case ( self : int ): UpperCAmelCase = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __snake_case ( self : str ): UpperCAmelCase = self.get_config() UpperCAmelCase = self.get_dummy_retriever() UpperCAmelCase = retriever.tokenizer UpperCAmelCase = np.array([0, 3] , dtype='''long''' ) UpperCAmelCase = tokenizer(['''Test question'''] ).input_ids UpperCAmelCase = tokenizer( ['''the fourth'''] , add_special_tokens=a__ , return_token_type_ids=a__ , return_attention_mask=a__ , ).input_ids UpperCAmelCase = config.reader_seq_len UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = retriever( a__ , a__ , answer_ids=a__ , max_length=a__ , return_tensors='''np''' ) self.assertEqual(len(a__ ) , 2 ) self.assertEqual(len(a__ ) , 2 ) self.assertEqual(len(a__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.get_config() UpperCAmelCase = self.get_dummy_retriever() UpperCAmelCase = retriever.tokenizer UpperCAmelCase = np.array([0, 3, 5] , dtype='''long''' ) UpperCAmelCase = tokenizer(['''Test question'''] ).input_ids UpperCAmelCase = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=a__ , return_token_type_ids=a__ , return_attention_mask=a__ , ).input_ids UpperCAmelCase = config.reader_seq_len UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = retriever( a__ , a__ , answer_ids=a__ , max_length=a__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , a__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , a__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path UpperCAmelCase = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , B'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: UpperCAmelCase = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) UpperCAmelCase = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , B'''This is the first record''' )
51
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ): pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _lowerCamelCase =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ): UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __snake_case ( self : int , a__ : Dict , a__ : Tuple ): pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __snake_case ( self : str ): pass @slow @require_torch def __snake_case ( self : Optional[Any] ): UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __snake_case ( self : Dict ): UpperCAmelCase = '''facebook/sam-vit-huge''' UpperCAmelCase = pipeline('''mask-generation''' , model=a__ ) UpperCAmelCase = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, ] , )
51
1
'''simple docstring''' from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput a__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : int , a__ : bool , a__ : Optional[int] = None , a__ : Optional[int] = None ): super().__init__() UpperCAmelCase = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" UpperCAmelCase = torch.zeros(a__ , a__ ) else: UpperCAmelCase = None UpperCAmelCase = torch.nn.Parameter(a__ ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =42 _lowerCamelCase =42 _lowerCamelCase =42 _lowerCamelCase =42 _lowerCamelCase =42 def __init__( self : List[str] , a__ : VQModel , a__ : CLIPTextModel , a__ : CLIPTokenizer , a__ : TransformeraDModel , a__ : VQDiffusionScheduler , a__ : LearnedClassifierFreeSamplingEmbeddings , ): super().__init__() self.register_modules( vqvae=a__ , transformer=a__ , text_encoder=a__ , tokenizer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) def __snake_case ( self : Any , a__ : Dict , a__ : Optional[int] , a__ : Optional[Any] ): UpperCAmelCase = len(a__ ) if isinstance(a__ , a__ ) else 1 # get prompt text embeddings UpperCAmelCase = self.tokenizer( a__ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , return_tensors='''pt''' , ) UpperCAmelCase = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCAmelCase = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCAmelCase = text_input_ids[:, : self.tokenizer.model_max_length] UpperCAmelCase = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 UpperCAmelCase = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=a__ ) # duplicate text embeddings for each generation per prompt UpperCAmelCase = prompt_embeds.repeat_interleave(a__ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: UpperCAmelCase = self.learned_classifier_free_sampling_embeddings.embeddings UpperCAmelCase = negative_prompt_embeds.unsqueeze(0 ).repeat(a__ , 1 , 1 ) else: UpperCAmelCase = [''''''] * batch_size UpperCAmelCase = text_input_ids.shape[-1] UpperCAmelCase = self.tokenizer( a__ , padding='''max_length''' , max_length=a__ , truncation=a__ , return_tensors='''pt''' , ) UpperCAmelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings UpperCAmelCase = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=a__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCAmelCase = negative_prompt_embeds.shape[1] UpperCAmelCase = negative_prompt_embeds.repeat(1 , a__ , 1 ) UpperCAmelCase = negative_prompt_embeds.view(batch_size * num_images_per_prompt , a__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCAmelCase = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Optional[Any] , a__ : Union[str, List[str]] , a__ : int = 100 , a__ : float = 5.0 , a__ : float = 1.0 , a__ : int = 1 , a__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a__ : Optional[torch.FloatTensor] = None , a__ : Optional[str] = "pil" , a__ : bool = True , a__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a__ : int = 1 , ): if isinstance(a__ , a__ ): UpperCAmelCase = 1 elif isinstance(a__ , a__ ): UpperCAmelCase = len(a__ ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(a__ )}" ) UpperCAmelCase = batch_size * num_images_per_prompt UpperCAmelCase = guidance_scale > 1.0 UpperCAmelCase = self._encode_prompt(a__ , a__ , a__ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(a__ , a__ ) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(a__ )}." ) # get the initial completely masked latents unless the user supplied it UpperCAmelCase = (batch_size, self.transformer.num_latent_pixels) if latents is None: UpperCAmelCase = self.transformer.num_vector_embeds - 1 UpperCAmelCase = torch.full(a__ , a__ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,''' f" {self.transformer.num_vector_embeds - 1} (inclusive)." ) UpperCAmelCase = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(a__ , device=self.device ) UpperCAmelCase = self.scheduler.timesteps.to(self.device ) UpperCAmelCase = latents for i, t in enumerate(self.progress_bar(a__ ) ): # expand the sample if we are doing classifier free guidance UpperCAmelCase = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` UpperCAmelCase = self.transformer(a__ , encoder_hidden_states=a__ , timestep=a__ ).sample if do_classifier_free_guidance: UpperCAmelCase, UpperCAmelCase = model_output.chunk(2 ) UpperCAmelCase = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(a__ , dim=1 , keepdim=a__ ) UpperCAmelCase = self.truncate(a__ , a__ ) # remove `log(0)`'s (`-inf`s) UpperCAmelCase = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 UpperCAmelCase = self.scheduler.step(a__ , timestep=a__ , sample=a__ , generator=a__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(a__ , a__ , a__ ) UpperCAmelCase = self.vqvae.config.vq_embed_dim UpperCAmelCase = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) UpperCAmelCase = self.vqvae.quantize.get_codebook_entry(a__ , shape=a__ ) UpperCAmelCase = self.vqvae.decode(a__ , force_not_quantize=a__ ).sample UpperCAmelCase = (image / 2 + 0.5).clamp(0 , 1 ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCAmelCase = self.numpy_to_pil(a__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a__ ) def __snake_case ( self : List[str] , a__ : torch.FloatTensor , a__ : float ): UpperCAmelCase, UpperCAmelCase = torch.sort(a__ , 1 , descending=a__ ) UpperCAmelCase = torch.exp(a__ ) UpperCAmelCase = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out UpperCAmelCase = torch.full_like(keep_mask[:, 0:1, :] , a__ ) UpperCAmelCase = torch.cat((all_true, keep_mask) , dim=1 ) UpperCAmelCase = keep_mask[:, :-1, :] UpperCAmelCase = keep_mask.gather(1 , indices.argsort(1 ) ) UpperCAmelCase = log_p_x_0.clone() UpperCAmelCase = -torch.inf # -inf = log(0) return rv
51
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
1
'''simple docstring''' from __future__ import annotations import csv import requests from bsa import BeautifulSoup def __snake_case ( SCREAMING_SNAKE_CASE_ : str = "" ) -> dict[str, float]: """simple docstring""" UpperCAmelCase = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250''' UpperCAmelCase = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE_ ).text , '''html.parser''' ) UpperCAmelCase = soup.find_all('''td''' , attrs='''titleColumn''' ) UpperCAmelCase = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) } def __snake_case ( SCREAMING_SNAKE_CASE_ : str = "IMDb_Top_250_Movies.csv" ) -> None: """simple docstring""" UpperCAmelCase = get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE_ , '''w''' , newline='''''' ) as out_file: UpperCAmelCase = csv.writer(SCREAMING_SNAKE_CASE_ ) writer.writerow(['''Movie title''', '''IMDb rating'''] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
51
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , a__ : List[str]="sayef/fsner-bert-base-uncased" ): super(a__ , self ).__init__() UpperCAmelCase = AutoModel.from_pretrained(a__ , return_dict=a__ ) UpperCAmelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCAmelCase = torch.nn.Softmax(dim=1 ) def __snake_case ( self : List[Any] , **a__ : Tuple ): return self.bert(**a__ ).last_hidden_state def __snake_case ( self : int , a__ : List[str] ): return token_embeddings.sum(2 , keepdim=a__ ) def __snake_case ( self : str , a__ : str , a__ : str , a__ : int=1 ): return self.softmax(T * self.cos(a__ , a__ ) ) def __snake_case ( self : Tuple , a__ : Tuple , a__ : str ): UpperCAmelCase = W_supports['''sizes'''].tolist() UpperCAmelCase = W_supports['''start_token_id'''].item() UpperCAmelCase = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = W_supports['''input_ids'''] == start_token_id UpperCAmelCase = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(a__ ): if i == 0: UpperCAmelCase = 0 else: UpperCAmelCase = support_sizes[i - 1] UpperCAmelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase = torch.vstack((p_starts, p_start) ) UpperCAmelCase = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase = p_start UpperCAmelCase = p_end return p_starts, p_ends
51
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Union[str, Any] = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="vit_mae" def __init__( self : Any , a__ : Any=768 , a__ : List[Any]=12 , a__ : Union[str, Any]=12 , a__ : Optional[Any]=3072 , a__ : Dict="gelu" , a__ : List[Any]=0.0 , a__ : int=0.0 , a__ : int=0.02 , a__ : Any=1e-1_2 , a__ : Any=224 , a__ : List[str]=16 , a__ : List[str]=3 , a__ : Optional[int]=True , a__ : str=16 , a__ : Union[str, Any]=512 , a__ : Dict=8 , a__ : int=2048 , a__ : List[str]=0.75 , a__ : Dict=False , **a__ : Optional[int] , ): super().__init__(**a__ ) UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = qkv_bias UpperCAmelCase = decoder_num_attention_heads UpperCAmelCase = decoder_hidden_size UpperCAmelCase = decoder_num_hidden_layers UpperCAmelCase = decoder_intermediate_size UpperCAmelCase = mask_ratio UpperCAmelCase = norm_pix_loss
51
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
1
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser a__ : Tuple = re.compile(R'\s+') def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Dict: """simple docstring""" return {"hash": hashlib.mda(re.sub(SCREAMING_SNAKE_CASE_ , '''''' , example['''content'''] ).encode('''utf-8''' ) ).hexdigest()} def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> str: """simple docstring""" UpperCAmelCase = [len(SCREAMING_SNAKE_CASE_ ) for line in example['''content'''].splitlines()] return {"line_mean": np.mean(SCREAMING_SNAKE_CASE_ ), "line_max": max(SCREAMING_SNAKE_CASE_ )} def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" UpperCAmelCase = np.mean([c.isalnum() for c in example['''content''']] ) return {"alpha_frac": alpha_frac} def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> Any: """simple docstring""" if example["hash"] in uniques: uniques.remove(example['''hash'''] ) return True else: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any=5 ) -> Optional[int]: """simple docstring""" UpperCAmelCase = ['''auto-generated''', '''autogenerated''', '''automatically generated'''] UpperCAmelCase = example['''content'''].splitlines() for _, line in zip(range(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str=5 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.05 ) -> List[Any]: """simple docstring""" UpperCAmelCase = ['''unit tests''', '''test file''', '''configuration file'''] UpperCAmelCase = example['''content'''].splitlines() UpperCAmelCase = 0 UpperCAmelCase = 0 # first test for _, line in zip(range(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test UpperCAmelCase = example['''content'''].count('''\n''' ) UpperCAmelCase = int(coeff * nlines ) for line in lines: count_config += line.lower().count('''config''' ) count_test += line.lower().count('''test''' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ['''def ''', '''class ''', '''for ''', '''while '''] UpperCAmelCase = example['''content'''].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any=4 ) -> int: """simple docstring""" UpperCAmelCase = example['''content'''].splitlines() UpperCAmelCase = 0 for line in lines: counter += line.lower().count('''=''' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" UpperCAmelCase = tokenizer(example['''content'''] , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] UpperCAmelCase = len(example['''content'''] ) / len(SCREAMING_SNAKE_CASE_ ) return {"ratio": ratio} def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" UpperCAmelCase = {} results.update(get_hash(SCREAMING_SNAKE_CASE_ ) ) results.update(line_stats(SCREAMING_SNAKE_CASE_ ) ) results.update(alpha_stats(SCREAMING_SNAKE_CASE_ ) ) results.update(char_token_ratio(SCREAMING_SNAKE_CASE_ ) ) results.update(is_autogenerated(SCREAMING_SNAKE_CASE_ ) ) results.update(is_config_or_test(SCREAMING_SNAKE_CASE_ ) ) results.update(has_no_keywords(SCREAMING_SNAKE_CASE_ ) ) results.update(has_few_assignments(SCREAMING_SNAKE_CASE_ ) ) return results def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if not check_uniques(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> str: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , '''rb''' ) as f_in: with gzip.open(str(SCREAMING_SNAKE_CASE_ ) + '''.gz''' , '''wb''' , compresslevel=6 ) as f_out: shutil.copyfileobj(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) os.unlink(SCREAMING_SNAKE_CASE_ ) # Settings a__ : List[Any] = HfArgumentParser(PreprocessingArguments) a__ : Tuple = parser.parse_args() if args.num_workers is None: a__ : Optional[Any] = multiprocessing.cpu_count() a__ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset a__ : List[str] = time.time() a__ : Any = load_dataset(args.dataset_name, split='train') print(F"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing a__ : Any = time.time() a__ : Union[str, Any] = ds.map(preprocess, num_proc=args.num_workers) print(F"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes a__ : Tuple = set(ds.unique('hash')) a__ : Any = len(uniques) / len(ds) print(F"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics a__ : str = time.time() a__ : Optional[Any] = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F"""Time to filter dataset: {time.time()-t_start:.2f}""") print(F"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: a__ : List[str] = time.time() a__ , a__ : str = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(F"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file a__ : Tuple = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) a__ : int = output_dir / 'data' data_dir.mkdir(exist_ok=True) a__ : Tuple = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): a__ : Any = str(data_dir / F"""file-{file_number+1:012}.json""") a__ : Dict = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"""Time to save dataset: {time.time()-t_start:.2f}""")
51
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Any = { 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xlm': ['XLMTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ 'XLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMForMultipleChoice', 'XLMForQuestionAnswering', 'XLMForQuestionAnsweringSimple', 'XLMForSequenceClassification', 'XLMForTokenClassification', 'XLMModel', 'XLMPreTrainedModel', 'XLMWithLMHeadModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMForMultipleChoice', 'TFXLMForQuestionAnsweringSimple', 'TFXLMForSequenceClassification', 'TFXLMForTokenClassification', 'TFXLMMainLayer', 'TFXLMModel', 'TFXLMPreTrainedModel', 'TFXLMWithLMHeadModel', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" print('''Loading config file...''' ) def flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" , SCREAMING_SNAKE_CASE_ : Dict="." ): UpperCAmelCase = [] for k, v in d.items(): UpperCAmelCase = parent_key + sep + k if parent_key else k if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sep=SCREAMING_SNAKE_CASE_ ).items() ) else: items.append((new_key, v) ) return dict(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = argparse.Namespace() with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as yaml_file: try: UpperCAmelCase = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=yaml.FullLoader ) UpperCAmelCase = flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ ) for k, v in flat_cfg.items(): setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) ) return config def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase = MobileViTVaConfig() UpperCAmelCase = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase = 151 UpperCAmelCase = 512 UpperCAmelCase = '''ade20k-id2label.json''' UpperCAmelCase = True elif task_name.startswith('''voc_''' ): UpperCAmelCase = 21 UpperCAmelCase = 512 UpperCAmelCase = '''pascal-voc-id2label.json''' UpperCAmelCase = True # orig_config UpperCAmelCase = load_orig_config_file(SCREAMING_SNAKE_CASE_ ) assert getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" UpperCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = val def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str=False ) -> int: """simple docstring""" if base_model: UpperCAmelCase = '''''' else: UpperCAmelCase = '''mobilevitv2.''' UpperCAmelCase = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase = k[8:] else: UpperCAmelCase = k if ".block." in k: UpperCAmelCase = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase = k_new.replace('''conv_1.''' , f"{model_prefix}conv_stem." ) for i in [1, 2]: if f"layer_{i}." in k: UpperCAmelCase = k_new.replace(f"layer_{i}." , f"{model_prefix}encoder.layer.{i-1}.layer." ) if ".exp_1x1." in k: UpperCAmelCase = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f"layer_{i}.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.0." , f"{model_prefix}encoder.layer.{i-1}.downsampling_layer." ) if f"layer_{i}.1.local_rep.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.0." , f"{model_prefix}encoder.layer.{i-1}.conv_kxk." ) if f"layer_{i}.1.local_rep.1." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.1." , f"{model_prefix}encoder.layer.{i-1}.conv_1x1." ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase = [0, 1] elif i == 4: UpperCAmelCase = [0, 1, 2, 3] elif i == 5: UpperCAmelCase = [0, 1, 2] for j in j_in: if f"layer_{i}.1.global_rep.{j}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j}." , f"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." ) if f"layer_{i}.1.global_rep.{j+1}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j+1}." , f"{model_prefix}encoder.layer.{i-1}.layernorm." ) if f"layer_{i}.1.conv_proj." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.conv_proj." , f"{model_prefix}encoder.layer.{i-1}.conv_projection." ) if "pre_norm_attn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> int: """simple docstring""" UpperCAmelCase = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(SCREAMING_SNAKE_CASE_ ) for k in keys_to_ignore: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> List[Any]: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = get_mobilevitva_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False else: UpperCAmelCase = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False # remove and rename some keys of load the original model UpperCAmelCase = checkpoint remove_unused_keys(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load modified state_dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase = outputs.logits UpperCAmelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {task_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 __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
51
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="megatron-bert" def __init__( self : Dict , a__ : Union[str, Any]=29056 , a__ : Dict=1024 , a__ : str=24 , a__ : Any=16 , a__ : Tuple=4096 , a__ : Optional[int]="gelu" , a__ : Tuple=0.1 , a__ : Tuple=0.1 , a__ : Any=512 , a__ : Optional[Any]=2 , a__ : str=0.02 , a__ : Optional[int]=1e-1_2 , a__ : Union[str, Any]=0 , a__ : Optional[Any]="absolute" , a__ : Dict=True , **a__ : Dict , ): super().__init__(pad_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache
51
1
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() a__ : Optional[int] = logging.get_logger(__name__) a__ : int = ['model.decoder.embed_positions.weights'] def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Tuple: """simple docstring""" if "emb" in name: UpperCAmelCase = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: UpperCAmelCase = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: UpperCAmelCase = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: UpperCAmelCase = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: UpperCAmelCase = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: UpperCAmelCase = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: UpperCAmelCase = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: UpperCAmelCase = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: UpperCAmelCase = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: UpperCAmelCase = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: UpperCAmelCase = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def __snake_case ( SCREAMING_SNAKE_CASE_ : OrderedDict , SCREAMING_SNAKE_CASE_ : int ) -> Tuple[Dict, Dict]: """simple docstring""" UpperCAmelCase = list(state_dict.keys() ) UpperCAmelCase = {} for key in keys: UpperCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = rename_keys(SCREAMING_SNAKE_CASE_ ) if "in_proj_weight" in key: # split fused qkv proj UpperCAmelCase = val[:hidden_size, :] UpperCAmelCase = val[hidden_size : 2 * hidden_size, :] UpperCAmelCase = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: UpperCAmelCase = val else: UpperCAmelCase = val return state_dict, enc_dec_proj_state_dict def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values UpperCAmelCase = 1_024 UpperCAmelCase = 24 UpperCAmelCase = 16 elif checkpoint == "medium": UpperCAmelCase = 1_536 UpperCAmelCase = 48 UpperCAmelCase = 24 elif checkpoint == "large": UpperCAmelCase = 2_048 UpperCAmelCase = 48 UpperCAmelCase = 32 else: raise ValueError(f"Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}." ) UpperCAmelCase = MusicgenDecoderConfig( hidden_size=SCREAMING_SNAKE_CASE_ , ffn_dim=hidden_size * 4 , num_hidden_layers=SCREAMING_SNAKE_CASE_ , num_attention_heads=SCREAMING_SNAKE_CASE_ , ) return config @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : Union[str, Any]="cpu" ) -> List[str]: """simple docstring""" UpperCAmelCase = MusicGen.get_pretrained(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = decoder_config_from_checkpoint(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = fairseq_model.lm.state_dict() UpperCAmelCase, UpperCAmelCase = rename_state_dict( SCREAMING_SNAKE_CASE_ , hidden_size=decoder_config.hidden_size ) UpperCAmelCase = TaEncoderModel.from_pretrained('''t5-base''' ) UpperCAmelCase = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) UpperCAmelCase = MusicgenForCausalLM(SCREAMING_SNAKE_CASE_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection UpperCAmelCase, UpperCAmelCase = decoder.load_state_dict(SCREAMING_SNAKE_CASE_ , strict=SCREAMING_SNAKE_CASE_ ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: raise ValueError(f"Missing key(s) in state_dict: {missing_keys}" ) if len(SCREAMING_SNAKE_CASE_ ) > 0: raise ValueError(f"Unexpected key(s) in state_dict: {unexpected_keys}" ) # init the composite model UpperCAmelCase = MusicgenForConditionalGeneration(text_encoder=SCREAMING_SNAKE_CASE_ , audio_encoder=SCREAMING_SNAKE_CASE_ , decoder=SCREAMING_SNAKE_CASE_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(SCREAMING_SNAKE_CASE_ ) # check we can do a forward pass UpperCAmelCase = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) UpperCAmelCase = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): UpperCAmelCase = model(input_ids=SCREAMING_SNAKE_CASE_ , decoder_input_ids=SCREAMING_SNAKE_CASE_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor UpperCAmelCase = AutoTokenizer.from_pretrained('''t5-base''' ) UpperCAmelCase = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) UpperCAmelCase = MusicgenProcessor(feature_extractor=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ ) # set the appropriate bos/pad token ids UpperCAmelCase = 2_048 UpperCAmelCase = 2_048 # set other default generation config params UpperCAmelCase = int(30 * audio_encoder.config.frame_rate ) UpperCAmelCase = True UpperCAmelCase = 3.0 if pytorch_dump_folder is not None: Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(f"Saving model {checkpoint} to {pytorch_dump_folder}" ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if repo_id: logger.info(f"Pushing model {checkpoint} to {repo_id}" ) model.push_to_hub(SCREAMING_SNAKE_CASE_ ) processor.push_to_hub(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) a__ : List[str] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
'''simple docstring''' from __future__ import annotations a__ : List[str] = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , a__ : dict[str, list[str]] , a__ : str ): UpperCAmelCase = graph # mapping node to its parent in resulting breadth first tree UpperCAmelCase = {} UpperCAmelCase = source_vertex def __snake_case ( self : Optional[int] ): UpperCAmelCase = {self.source_vertex} UpperCAmelCase = None UpperCAmelCase = [self.source_vertex] # first in first out queue while queue: UpperCAmelCase = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(a__ ) UpperCAmelCase = vertex queue.append(a__ ) def __snake_case ( self : Any , a__ : str ): if target_vertex == self.source_vertex: return self.source_vertex UpperCAmelCase = self.parent.get(a__ ) if target_vertex_parent is None: UpperCAmelCase = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(a__ ) return self.shortest_path(a__ ) + f"->{target_vertex}" if __name__ == "__main__": a__ : Tuple = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
51
1
'''simple docstring''' import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging a__ : int = logging.get_logger(__name__) a__ : Any = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} # See all LED models at https://huggingface.co/models?filter=LED a__ : str = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } a__ : Any = { 'allenai/led-base-16384': 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def __snake_case ( ) -> List[str]: """simple docstring""" UpperCAmelCase = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) UpperCAmelCase = bs[:] UpperCAmelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE_ ) cs.append(2**8 + n ) n += 1 UpperCAmelCase = [chr(SCREAMING_SNAKE_CASE_ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase = set() UpperCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase = char return pairs class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =VOCAB_FILES_NAMES _lowerCamelCase =PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase =["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , a__ : Any , a__ : Any , a__ : Optional[int]="replace" , a__ : Optional[int]="<s>" , a__ : int="</s>" , a__ : List[Any]="</s>" , a__ : Dict="<s>" , a__ : int="<unk>" , a__ : List[Any]="<pad>" , a__ : Any="<mask>" , a__ : List[Any]=False , **a__ : str , ): UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else bos_token UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else eos_token UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else sep_token UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else cls_token UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else unk_token UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else mask_token super().__init__( errors=a__ , bos_token=a__ , eos_token=a__ , unk_token=a__ , sep_token=a__ , cls_token=a__ , pad_token=a__ , mask_token=a__ , add_prefix_space=a__ , **a__ , ) with open(a__ , encoding='''utf-8''' ) as vocab_handle: UpperCAmelCase = json.load(a__ ) UpperCAmelCase = {v: k for k, v in self.encoder.items()} UpperCAmelCase = errors # how to handle errors in decoding UpperCAmelCase = bytes_to_unicode() UpperCAmelCase = {v: k for k, v in self.byte_encoder.items()} with open(a__ , encoding='''utf-8''' ) as merges_handle: UpperCAmelCase = merges_handle.read().split('''\n''' )[1:-1] UpperCAmelCase = [tuple(merge.split() ) for merge in bpe_merges] UpperCAmelCase = dict(zip(a__ , range(len(a__ ) ) ) ) UpperCAmelCase = {} UpperCAmelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCAmelCase = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def __snake_case ( self : Dict ): return len(self.encoder ) def __snake_case ( self : List[Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def __snake_case ( self : Optional[Any] , a__ : Union[str, Any] ): if token in self.cache: return self.cache[token] UpperCAmelCase = tuple(a__ ) UpperCAmelCase = get_pairs(a__ ) if not pairs: return token while True: UpperCAmelCase = min(a__ , key=lambda a__ : self.bpe_ranks.get(a__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase, UpperCAmelCase = bigram UpperCAmelCase = [] UpperCAmelCase = 0 while i < len(a__ ): try: UpperCAmelCase = word.index(a__ , a__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCAmelCase = j if word[i] == first and i < len(a__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase = tuple(a__ ) UpperCAmelCase = new_word if len(a__ ) == 1: break else: UpperCAmelCase = get_pairs(a__ ) UpperCAmelCase = ''' '''.join(a__ ) UpperCAmelCase = word return word def __snake_case ( self : str , a__ : str ): UpperCAmelCase = [] for token in re.findall(self.pat , a__ ): UpperCAmelCase = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(a__ ).split(''' ''' ) ) return bpe_tokens def __snake_case ( self : Optional[Any] , a__ : Dict ): return self.encoder.get(a__ , self.encoder.get(self.unk_token ) ) def __snake_case ( self : Any , a__ : int ): return self.decoder.get(a__ ) def __snake_case ( self : Optional[int] , a__ : Tuple ): UpperCAmelCase = ''''''.join(a__ ) UpperCAmelCase = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __snake_case ( self : Union[str, Any] , a__ : str , a__ : Optional[str] = None ): if not os.path.isdir(a__ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCAmelCase = os.path.join( a__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase = os.path.join( a__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=a__ , ensure_ascii=a__ ) + '''\n''' ) UpperCAmelCase = 0 with open(a__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda a__ : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ''' Please check that the tokenizer is not corrupted!''' ) UpperCAmelCase = token_index writer.write(''' '''.join(a__ ) + '''\n''' ) index += 1 return vocab_file, merge_file def __snake_case ( self : Optional[Any] , a__ : List[int] , a__ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase = [self.cls_token_id] UpperCAmelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __snake_case ( self : Tuple , a__ : List[int] , a__ : Optional[List[int]] = None , a__ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a__ , token_ids_a=a__ , already_has_special_tokens=a__ ) if token_ids_a is None: return [1] + ([0] * len(a__ )) + [1] return [1] + ([0] * len(a__ )) + [1, 1] + ([0] * len(a__ )) + [1] def __snake_case ( self : int , a__ : List[int] , a__ : Optional[List[int]] = None ): UpperCAmelCase = [self.sep_token_id] UpperCAmelCase = [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 __snake_case ( self : Union[str, Any] , a__ : List[str] , a__ : Union[str, Any]=False , **a__ : Dict ): UpperCAmelCase = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(a__ ) > 0 and not text[0].isspace()): UpperCAmelCase = ''' ''' + text return (text, kwargs) def __snake_case ( self : Optional[Any] , a__ : Union[Dict[str, EncodedInput], BatchEncoding] , a__ : Optional[int] = None , a__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , a__ : Optional[int] = None , a__ : Optional[bool] = None , ): UpperCAmelCase = super()._pad( encoded_inputs=a__ , max_length=a__ , padding_strategy=a__ , pad_to_multiple_of=a__ , return_attention_mask=a__ , ) # Load from model defaults if return_attention_mask is None: UpperCAmelCase = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCAmelCase = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCAmelCase = len(encoded_inputs['''global_attention_mask'''] ) != len(a__ ) if needs_to_be_padded: UpperCAmelCase = len(a__ ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCAmelCase = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": UpperCAmelCase = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : Tuple = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys a__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 a__ : str = get_tests_dir('fixtures') class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Any ): # A mock response for an HTTP head request to emulate server down UpperCAmelCase = mock.Mock() UpperCAmelCase = 500 UpperCAmelCase = {} UpperCAmelCase = HTTPError UpperCAmelCase = {} # Download this model to make sure it's in the cache. UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=a__ ) as mock_head: UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # This check we did call the fake head request mock_head.assert_called() def __snake_case ( self : Any ): # This test is for deprecated behavior and can be removed in v5 UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json''' ) @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def __snake_case ( cls : Any ): UpperCAmelCase = TOKEN HfFolder.save_token(a__ ) @classmethod def __snake_case ( cls : Union[str, Any] ): try: delete_repo(token=cls._token , repo_id='''test-feature-extractor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-feature-extractor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-feature-extractor''' ) except HTTPError: pass def __snake_case ( self : Optional[Any] ): UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''test-feature-extractor''' , use_auth_token=self._token ) UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a__ , repo_id='''test-feature-extractor''' , push_to_hub=a__ , use_auth_token=self._token ) UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) def __snake_case ( self : List[Any] ): UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' , use_auth_token=self._token ) UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a__ , repo_id='''valid_org/test-feature-extractor-org''' , push_to_hub=a__ , use_auth_token=self._token ) UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) def __snake_case ( self : str ): CustomFeatureExtractor.register_for_auto_class() UpperCAmelCase = CustomFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''test-dynamic-feature-extractor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''} , ) UpperCAmelCase = AutoFeatureExtractor.from_pretrained( f"{USER}/test-dynamic-feature-extractor" , trust_remote_code=a__ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , '''CustomFeatureExtractor''' )
51
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Any = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' from __future__ import annotations def __snake_case ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> float: """simple docstring""" if days_between_payments <= 0: raise ValueError('''days_between_payments must be > 0''' ) if daily_interest_rate < 0: raise ValueError('''daily_interest_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * daily_interest_rate * days_between_payments def __snake_case ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" if number_of_compounding_periods <= 0: raise ValueError('''number_of_compounding_periods must be > 0''' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('''nominal_annual_interest_rate_percentage must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" if number_of_years <= 0: raise ValueError('''number_of_years must be > 0''' ) if nominal_annual_percentage_rate < 0: raise ValueError('''nominal_annual_percentage_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return compound_interest( SCREAMING_SNAKE_CASE_ , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from math import factorial def __snake_case ( SCREAMING_SNAKE_CASE_ : int = 100 ) -> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
51
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =42 class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : List[Any] , a__ : int = 3 , a__ : int = 3 , a__ : Tuple[str] = ("DownEncoderBlock2D",) , a__ : Tuple[str] = ("UpDecoderBlock2D",) , a__ : Tuple[int] = (64,) , a__ : int = 1 , a__ : str = "silu" , a__ : int = 3 , a__ : int = 32 , a__ : int = 256 , a__ : int = 32 , a__ : Optional[int] = None , a__ : float = 0.18_215 , a__ : str = "group" , ): super().__init__() # pass init params to Encoder UpperCAmelCase = Encoder( in_channels=a__ , out_channels=a__ , down_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , act_fn=a__ , norm_num_groups=a__ , double_z=a__ , ) UpperCAmelCase = vq_embed_dim if vq_embed_dim is not None else latent_channels UpperCAmelCase = nn.Convad(a__ , a__ , 1 ) UpperCAmelCase = VectorQuantizer(a__ , a__ , beta=0.25 , remap=a__ , sane_index_shape=a__ ) UpperCAmelCase = nn.Convad(a__ , a__ , 1 ) # pass init params to Decoder UpperCAmelCase = Decoder( in_channels=a__ , out_channels=a__ , up_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , act_fn=a__ , norm_num_groups=a__ , norm_type=a__ , ) @apply_forward_hook def __snake_case ( self : Tuple , a__ : torch.FloatTensor , a__ : bool = True ): UpperCAmelCase = self.encoder(a__ ) UpperCAmelCase = self.quant_conv(a__ ) if not return_dict: return (h,) return VQEncoderOutput(latents=a__ ) @apply_forward_hook def __snake_case ( self : str , a__ : torch.FloatTensor , a__ : bool = False , a__ : bool = True ): # also go through quantization layer if not force_not_quantize: UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = self.quantize(a__ ) else: UpperCAmelCase = h UpperCAmelCase = self.post_quant_conv(a__ ) UpperCAmelCase = self.decoder(a__ , quant if self.config.norm_type == '''spatial''' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) def __snake_case ( self : List[Any] , a__ : torch.FloatTensor , a__ : bool = True ): UpperCAmelCase = sample UpperCAmelCase = self.encode(a__ ).latents UpperCAmelCase = self.decode(a__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=a__ )
51
'''simple docstring''' import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =StableUnCLIPPipeline _lowerCamelCase =TEXT_TO_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _lowerCamelCase =False def __snake_case ( self : str ): UpperCAmelCase = 32 UpperCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=a__ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) UpperCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=a__ , num_layers=1 , ) torch.manual_seed(0 ) UpperCAmelCase = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1000 , clip_sample=a__ , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) UpperCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=a__ ) UpperCAmelCase = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=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 , ) ) torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a__ , layers_per_block=1 , upcast_attention=a__ , use_linear_projection=a__ , ) torch.manual_seed(0 ) UpperCAmelCase = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=a__ , steps_offset=1 , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL() UpperCAmelCase = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def __snake_case ( self : str , a__ : Dict , a__ : List[str]=0 ): if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __snake_case ( self : List[Any] ): UpperCAmelCase = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=a__ ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[int] ): UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = pipe('''anime turle''' , generator=a__ , output_type='''np''' ) UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ ) def __snake_case ( self : str ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
51
1
'''simple docstring''' import gc import threading import time import psutil import torch class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple ): UpperCAmelCase = psutil.Process() UpperCAmelCase = False def __snake_case ( self : Optional[int] ): UpperCAmelCase = -1 while True: UpperCAmelCase = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def __snake_case ( self : Dict ): UpperCAmelCase = True UpperCAmelCase = threading.Thread(target=self.peak_monitor ) UpperCAmelCase = True self.thread.start() def __snake_case ( self : str ): UpperCAmelCase = False self.thread.join() return self.cpu_memory_peak a__ : List[Any] = PeakCPUMemory() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = {'''time''': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem UpperCAmelCase = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): UpperCAmelCase = torch.cuda.memory_allocated(SCREAMING_SNAKE_CASE_ ) torch.cuda.reset_peak_memory_stats() return measures def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = {'''time''': time.time() - start_measures['''time''']} gc.collect() torch.cuda.empty_cache() # CPU mem UpperCAmelCase = (psutil.Process().memory_info().rss - start_measures['''cpu''']) / 2**20 UpperCAmelCase = (cpu_peak_tracker.stop() - start_measures['''cpu''']) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): UpperCAmelCase = (torch.cuda.memory_allocated(SCREAMING_SNAKE_CASE_ ) - start_measures[str(SCREAMING_SNAKE_CASE_ )]) / 2**20 UpperCAmelCase = (torch.cuda.max_memory_allocated(SCREAMING_SNAKE_CASE_ ) - start_measures[str(SCREAMING_SNAKE_CASE_ )]) / 2**20 return measures def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: """simple docstring""" print(f"{description}:" ) print(f"- Time: {measures['time']:.2f}s" ) for i in range(torch.cuda.device_count() ): print(f"- GPU {i} allocated: {measures[str(SCREAMING_SNAKE_CASE_ )]:.2f}MiB" ) UpperCAmelCase = measures[f"{i}-peak"] print(f"- GPU {i} peak: {peak:.2f}MiB" ) print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB" ) print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB" )
51
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" if not head: return True # split the list to two parts UpperCAmelCase, UpperCAmelCase = head.next, head while fast and fast.next: UpperCAmelCase = fast.next.next UpperCAmelCase = slow.next UpperCAmelCase = slow.next UpperCAmelCase = None # Don't forget here! But forget still works! # reverse the second part UpperCAmelCase = None while second: UpperCAmelCase = second.next UpperCAmelCase = node UpperCAmelCase = second UpperCAmelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False UpperCAmelCase = node.next UpperCAmelCase = head.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Union[str, Any]: """simple docstring""" if not head or not head.next: return True # 1. Get the midpoint (slow) UpperCAmelCase = UpperCAmelCase = UpperCAmelCase = head while fast and fast.next: UpperCAmelCase, UpperCAmelCase = fast.next.next, slow.next # 2. Push the second half into the stack UpperCAmelCase = [slow.val] while slow.next: UpperCAmelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False UpperCAmelCase = cur.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Tuple: """simple docstring""" if not head or not head.next: return True UpperCAmelCase = {} UpperCAmelCase = 0 while head: if head.val in d: d[head.val].append(SCREAMING_SNAKE_CASE_ ) else: UpperCAmelCase = [pos] UpperCAmelCase = head.next pos += 1 UpperCAmelCase = pos - 1 UpperCAmelCase = 0 for v in d.values(): if len(SCREAMING_SNAKE_CASE_ ) % 2 != 0: middle += 1 else: UpperCAmelCase = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): if v[i] + v[len(SCREAMING_SNAKE_CASE_ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
51
1
'''simple docstring''' import enum import shutil import sys a__ , a__ : List[str] = shutil.get_terminal_size() a__ : Any = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): '''simple docstring''' _lowerCamelCase =0 _lowerCamelCase =1 def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any]="" ) -> Tuple: """simple docstring""" sys.stdout.write(str(SCREAMING_SNAKE_CASE_ ) + end ) sys.stdout.flush() def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" ) -> str: """simple docstring""" forceWrite(f"\u001b[{color}m{content}\u001b[0m" , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> Tuple: """simple docstring""" forceWrite('''\r''' ) def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ) -> List[Any]: """simple docstring""" forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}" ) def __snake_case ( ) -> Union[str, Any]: """simple docstring""" forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __snake_case ( ) -> Union[str, Any]: """simple docstring""" reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
51
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Tuple , a__ : List[Any]=None , a__ : str=None , **a__ : Tuple ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Optional[Any] , a__ : Optional[int]=None , a__ : List[str]=None , a__ : int=None , **a__ : Tuple ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : List[str] , *a__ : Union[str, Any] , **a__ : Optional[int] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : int , *a__ : Optional[int] , **a__ : int ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __snake_case ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a__ , ) return self.image_processor_class @property def __snake_case ( self : List[Any] ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a__ , ) return self.image_processor
51
1
'''simple docstring''' # using dfs for finding eulerian path traversal def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str]=None ) -> List[Any]: """simple docstring""" UpperCAmelCase = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCAmelCase, UpperCAmelCase = True, True UpperCAmelCase = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return path def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple ) -> Any: """simple docstring""" UpperCAmelCase = 0 UpperCAmelCase = -1 for i in range(SCREAMING_SNAKE_CASE_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCAmelCase = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[str]: """simple docstring""" UpperCAmelCase = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCAmelCase, UpperCAmelCase = check_circuit_or_path(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if check == 3: print('''graph is not Eulerian''' ) print('''no path''' ) return UpperCAmelCase = 1 if check == 2: UpperCAmelCase = odd_node print('''graph has a Euler path''' ) if check == 1: print('''graph has a Euler cycle''' ) UpperCAmelCase = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCAmelCase = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCAmelCase = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCAmelCase = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCAmelCase = { 1: [], 2: [] # all degree is zero } UpperCAmelCase = 10 check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_euler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
51
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =XGLMTokenizer _lowerCamelCase =XGLMTokenizerFast _lowerCamelCase =True _lowerCamelCase =True def __snake_case ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[Any] ): UpperCAmelCase = '''<pad>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(a__ ) , 1008 ) def __snake_case ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(a__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( a__ , [ 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''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ 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 __snake_case ( self : Optional[Any] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def __snake_case ( self : Optional[int] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=a__ ) UpperCAmelCase = pickle.dumps(a__ ) pickle.loads(a__ ) def __snake_case ( self : Tuple ): if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = '''I was born in 92000, and this is falsé.''' UpperCAmelCase = tokenizer.tokenize(a__ ) UpperCAmelCase = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = tokenizer.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __snake_case ( self : int ): UpperCAmelCase = '''Hello World!''' UpperCAmelCase = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : List[str] ): UpperCAmelCase = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off UpperCAmelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : Any ): # fmt: off UpperCAmelCase = { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name='''facebook/xglm-564M''' , padding=a__ , )
51
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , a__ : Dict , a__ : List[Any]=3 , a__ : str=32 , a__ : List[Any]=3 , a__ : str=10 , a__ : List[Any]=[10, 20, 30, 40] , a__ : Dict=[1, 1, 2, 1] , a__ : Tuple=True , a__ : List[Any]=True , a__ : List[str]="relu" , a__ : List[Any]=3 , a__ : Union[str, Any]=None , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = num_channels UpperCAmelCase = embeddings_size UpperCAmelCase = hidden_sizes UpperCAmelCase = depths UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_act UpperCAmelCase = num_labels UpperCAmelCase = scope UpperCAmelCase = len(a__ ) def __snake_case ( self : List[str] ): UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def __snake_case ( self : Any ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __snake_case ( self : Optional[int] , a__ : List[Any] , a__ : List[Any] , a__ : Tuple ): UpperCAmelCase = RegNetModel(config=a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __snake_case ( self : int , a__ : List[Any] , a__ : Union[str, Any] , a__ : Union[str, Any] ): UpperCAmelCase = self.num_labels UpperCAmelCase = RegNetForImageClassification(a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(RegNetModel, RegNetForImageClassification) if is_torch_available() else () _lowerCamelCase =( {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} if is_torch_available() else {} ) _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : List[str] ): UpperCAmelCase = RegNetModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ , has_text_modality=a__ ) def __snake_case ( self : Tuple ): 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 __snake_case ( self : Optional[int] ): return @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __snake_case ( self : Optional[int] ): pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __snake_case ( self : Tuple ): pass def __snake_case ( self : int ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(config=a__ ) for name, module in model.named_modules(): if isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) def __snake_case ( self : Dict ): def check_hidden_states_output(a__ : List[Any] , a__ : List[Any] , a__ : str ): UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase = self.model_tester.num_stages self.assertEqual(len(a__ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCAmelCase = layer_type UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) def __snake_case ( self : str ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def __snake_case ( self : str ): for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = RegNetModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def __snake_case ( ) -> Dict: """simple docstring""" UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def __snake_case ( self : int ): return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __snake_case ( self : List[str] ): UpperCAmelCase = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(a__ ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=a__ , return_tensors='''pt''' ).to(a__ ) # forward pass with torch.no_grad(): UpperCAmelCase = model(**a__ ) # verify the logits UpperCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) UpperCAmelCase = torch.tensor([-0.4_180, -1.5_051, -3.4_836] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) )
51
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : str = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> YolosConfig: """simple docstring""" UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 UpperCAmelCase = [800, 1_333] UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase = 330 UpperCAmelCase = 14 UpperCAmelCase = 6 UpperCAmelCase = 1_320 elif "yolos_s" in yolos_name: UpperCAmelCase = 384 UpperCAmelCase = 1_536 UpperCAmelCase = 12 UpperCAmelCase = 6 elif "yolos_b" in yolos_name: UpperCAmelCase = [800, 1_344] UpperCAmelCase = 91 UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''coco-detection-id2label.json''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosConfig , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[: config.hidden_size, :] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if "backbone" in name: UpperCAmelCase = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: UpperCAmelCase = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: UpperCAmelCase = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: UpperCAmelCase = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: UpperCAmelCase = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCAmelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: UpperCAmelCase = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCAmelCase = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCAmelCase = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCAmelCase = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCAmelCase = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCAmelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCAmelCase = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: UpperCAmelCase = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: UpperCAmelCase = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: UpperCAmelCase = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: UpperCAmelCase = key.split('''.''' ) UpperCAmelCase = int(key_split[2] ) UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase = val[:dim, :] UpperCAmelCase = val[ dim : dim * 2, : ] UpperCAmelCase = val[-dim:, :] else: UpperCAmelCase = val[:dim] UpperCAmelCase = val[dim : dim * 2] UpperCAmelCase = val[-dim:] else: UpperCAmelCase = val return orig_state_dict def __snake_case ( ) -> torch.Tensor: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" UpperCAmelCase = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' )['''model'''] # load 🤗 model UpperCAmelCase = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCAmelCase = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase = 800 if yolos_name != '''yolos_ti''' else 512 UpperCAmelCase = YolosImageProcessor(format='''coco_detection''' , size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase, UpperCAmelCase = outputs.logits, outputs.pred_boxes UpperCAmelCase, UpperCAmelCase = None, None if yolos_name == "yolos_ti": UpperCAmelCase = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) UpperCAmelCase = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) UpperCAmelCase = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) UpperCAmelCase = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": UpperCAmelCase = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) UpperCAmelCase = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {yolos_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: UpperCAmelCase = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) model.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.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.' ) a__ : Optional[Any] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
51
1
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : int ) -> list: """simple docstring""" if bit_count < 0: raise ValueError('''The given input must be positive''' ) # get the generated string sequence UpperCAmelCase = gray_code_sequence_string(SCREAMING_SNAKE_CASE_ ) # # convert them to integers for i in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCAmelCase = int(sequence[i] , 2 ) return sequence def __snake_case ( SCREAMING_SNAKE_CASE_ : int ) -> list: """simple docstring""" if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] UpperCAmelCase = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits UpperCAmelCase = gray_code_sequence_string(bit_count - 1 ) UpperCAmelCase = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): UpperCAmelCase = '''0''' + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE_ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): UpperCAmelCase = '''1''' + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE_ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a__ : List[Any] = logging.get_logger(__name__) a__ : int = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a__ : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] a__ : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="whisper" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[Any] , a__ : Any=51865 , a__ : Any=80 , a__ : Dict=6 , a__ : int=4 , a__ : int=6 , a__ : str=4 , a__ : int=1536 , a__ : Optional[Any]=1536 , a__ : str=0.0 , a__ : Optional[int]=0.0 , a__ : Optional[int]=50257 , a__ : int=True , a__ : Optional[int]=True , a__ : str="gelu" , a__ : List[str]=256 , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Any=0.0 , a__ : str=0.02 , a__ : str=False , a__ : int=1500 , a__ : Tuple=448 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Tuple=None , a__ : List[Any]=[220, 50256] , a__ : Optional[int]=False , a__ : Optional[Any]=256 , a__ : Any=False , a__ : int=0.05 , a__ : Optional[Any]=10 , a__ : Dict=2 , a__ : Optional[Any]=0.0 , a__ : Tuple=10 , a__ : Any=0 , a__ : str=7 , **a__ : Any , ): UpperCAmelCase = vocab_size UpperCAmelCase = num_mel_bins UpperCAmelCase = d_model UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size UpperCAmelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks UpperCAmelCase = median_filter_width super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , suppress_tokens=a__ , begin_suppress_tokens=a__ , **a__ , ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : List[str] ): UpperCAmelCase = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: UpperCAmelCase = {0: '''batch'''} else: UpperCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs def __snake_case ( self : str , a__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a__ : int = -1 , a__ : int = -1 , a__ : bool = False , a__ : Optional["TensorType"] = None , a__ : int = 22050 , a__ : float = 5.0 , a__ : int = 220 , ): UpperCAmelCase = OrderedDict() UpperCAmelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a__ , framework=a__ , sampling_rate=a__ , time_duration=a__ , frequency=a__ , ) UpperCAmelCase = encoder_inputs['''input_features'''].shape[2] UpperCAmelCase = encoder_sequence_length // 2 if self.use_past else seq_length UpperCAmelCase = super().generate_dummy_inputs( preprocessor.tokenizer , a__ , a__ , a__ , a__ ) UpperCAmelCase = encoder_inputs.pop('''input_features''' ) UpperCAmelCase = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: UpperCAmelCase = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __snake_case ( self : Dict ): return 1e-3
51
1
'''simple docstring''' from math import loga def __snake_case ( SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =LEDConfig _lowerCamelCase ={} _lowerCamelCase ="gelu" def __init__( self : Tuple , a__ : Any , a__ : int=13 , a__ : List[Any]=7 , a__ : int=True , a__ : Union[str, Any]=False , a__ : Tuple=99 , a__ : Any=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : List[Any]=37 , a__ : List[Any]=0.1 , a__ : Any=0.1 , a__ : Optional[int]=20 , a__ : List[Any]=2 , a__ : Union[str, Any]=1 , a__ : List[Any]=0 , a__ : Union[str, Any]=4 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after UpperCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests UpperCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) UpperCAmelCase = prepare_led_inputs_dict(a__ , a__ , a__ ) UpperCAmelCase = tf.concat( [tf.zeros_like(a__ )[:, :-1], tf.ones_like(a__ )[:, -1:]] , axis=-1 , ) UpperCAmelCase = global_attention_mask return config, inputs_dict def __snake_case ( self : Optional[int] , a__ : List[str] , a__ : int ): UpperCAmelCase = TFLEDModel(config=a__ ).get_decoder() UpperCAmelCase = inputs_dict['''input_ids'''] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(a__ , attention_mask=a__ , use_cache=a__ ) UpperCAmelCase, UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(a__ , attention_mask=a__ )[0] UpperCAmelCase = model(a__ , attention_mask=a__ , past_key_values=a__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(a__ , a__ , rtol=1e-3 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=None , ) -> Dict: """simple docstring""" if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowerCamelCase =(TFLEDForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase =( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : Optional[Any] ): UpperCAmelCase = TFLEDModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ ) def __snake_case ( self : int ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = tf.zeros_like(inputs_dict['''attention_mask'''] ) UpperCAmelCase = 2 UpperCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) UpperCAmelCase = True UpperCAmelCase = self.model_tester.seq_length UpperCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(a__ : Tuple ): UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(a__ : int ): UpperCAmelCase = [t.numpy() for t in outputs.encoder_attentions] UpperCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = len(a__ ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) if self.is_encoder_decoder: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_decoder_attentions_output(a__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) ) self.assertEqual(model.config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __snake_case ( self : Any ): pass def __snake_case ( self : Union[str, Any] ): # TODO: Head-masking not yet implement pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> Tuple: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE_ , dtype=tf.intaa ) a__ : int = 1e-4 @slow @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, 768) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 ) def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 , rtol=1e-3 )
51
1
'''simple docstring''' import string def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" UpperCAmelCase = '''''' for i in sequence: UpperCAmelCase = ord(SCREAMING_SNAKE_CASE_ ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" UpperCAmelCase = string.ascii_letters UpperCAmelCase = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(SCREAMING_SNAKE_CASE_ )] if c in letters else c for c in sequence ) def __snake_case ( ) -> None: """simple docstring""" from timeit import timeit print('''Running performance benchmarks...''' ) UpperCAmelCase = '''from string import printable ; from __main__ import atbash, atbash_slow''' print(f"> atbash_slow(): {timeit('atbash_slow(printable)' , setup=SCREAMING_SNAKE_CASE_ )} seconds" ) print(f"> atbash(): {timeit('atbash(printable)' , setup=SCREAMING_SNAKE_CASE_ )} seconds" ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(F"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : List[Any] = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' import inspect import unittest from transformers import YolosConfig 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , a__ : List[Any] , a__ : str=13 , a__ : Tuple=[30, 30] , a__ : int=2 , a__ : Any=3 , a__ : Any=True , a__ : int=True , a__ : List[Any]=32 , a__ : int=5 , a__ : int=4 , a__ : Optional[Any]=37 , a__ : Optional[int]="gelu" , a__ : Tuple=0.1 , a__ : Any=0.1 , a__ : Union[str, Any]=10 , a__ : Any=0.02 , a__ : str=3 , a__ : Tuple=None , a__ : str=8 , a__ : List[str]=10 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = scope UpperCAmelCase = n_targets UpperCAmelCase = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens UpperCAmelCase = (image_size[1] // patch_size) * (image_size[0] // patch_size) UpperCAmelCase = num_patches + 1 + self.num_detection_tokens def __snake_case ( self : List[str] ): UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) UpperCAmelCase = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) UpperCAmelCase = [] for i in range(self.batch_size ): UpperCAmelCase = {} UpperCAmelCase = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=a__ ) UpperCAmelCase = torch.rand(self.n_targets , 4 , device=a__ ) labels.append(a__ ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def __snake_case ( self : Any ): return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def __snake_case ( self : int , a__ : Tuple , a__ : Optional[int] , a__ : str ): UpperCAmelCase = YolosModel(config=a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(a__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def __snake_case ( self : Optional[int] , a__ : Union[str, Any] , a__ : str , a__ : int ): UpperCAmelCase = YolosForObjectDetection(a__ ) model.to(a__ ) model.eval() UpperCAmelCase = model(pixel_values=a__ ) UpperCAmelCase = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) UpperCAmelCase = model(pixel_values=a__ , labels=a__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(YolosModel, YolosForObjectDetection) if is_torch_available() else () _lowerCamelCase =( {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} ) _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : List[Any] , a__ : List[str] , a__ : Dict , a__ : Dict=False ): UpperCAmelCase = super()._prepare_for_class(a__ , a__ , return_labels=a__ ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": UpperCAmelCase = [] for i in range(self.model_tester.batch_size ): UpperCAmelCase = {} UpperCAmelCase = torch.ones( size=(self.model_tester.n_targets,) , device=a__ , dtype=torch.long ) UpperCAmelCase = torch.ones( self.model_tester.n_targets , 4 , device=a__ , dtype=torch.float ) labels.append(a__ ) UpperCAmelCase = labels return inputs_dict def __snake_case ( self : Dict ): UpperCAmelCase = YolosModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __snake_case ( self : Optional[Any] ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): # YOLOS does not use inputs_embeds pass def __snake_case ( self : int ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , a__ ) def __snake_case ( self : List[str] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = True # in YOLOS, the seq_len is different UpperCAmelCase = self.model_tester.expected_seq_len for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = outputs.attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = outputs.attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) UpperCAmelCase = len(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = 1 self.assertEqual(out_len + added_hidden_states , len(a__ ) ) UpperCAmelCase = outputs.attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def __snake_case ( self : Union[str, Any] ): def check_hidden_states_output(a__ : Optional[Any] , a__ : Dict , a__ : Optional[Any] ): UpperCAmelCase = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): UpperCAmelCase = model(**self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = outputs.hidden_states UpperCAmelCase = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(a__ ) , a__ ) # YOLOS has a different seq_length UpperCAmelCase = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase = True check_hidden_states_output(a__ , a__ , a__ ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*a__ ) @slow def __snake_case ( self : str ): for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = YolosModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def __snake_case ( ) -> Optional[int]: """simple docstring""" UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def __snake_case ( self : List[str] ): return AutoImageProcessor.from_pretrained('''hustvl/yolos-small''' ) if is_vision_available() else None @slow def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = YolosForObjectDetection.from_pretrained('''hustvl/yolos-small''' ).to(a__ ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=a__ , return_tensors='''pt''' ).to(a__ ) # forward pass with torch.no_grad(): UpperCAmelCase = model(inputs.pixel_values ) # verify outputs UpperCAmelCase = torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , a__ ) UpperCAmelCase = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] , device=a__ , ) UpperCAmelCase = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] , device=a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , a__ , atol=1e-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , a__ , atol=1e-4 ) ) # verify postprocessing UpperCAmelCase = image_processor.post_process_object_detection( a__ , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] UpperCAmelCase = torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861] ).to(a__ ) UpperCAmelCase = [75, 75, 17, 63, 17] UpperCAmelCase = torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495] ).to(a__ ) self.assertEqual(len(results['''scores'''] ) , 5 ) self.assertTrue(torch.allclose(results['''scores'''] , a__ , atol=1e-4 ) ) self.assertSequenceEqual(results['''labels'''].tolist() , a__ ) self.assertTrue(torch.allclose(results['''boxes'''][0, :] , a__ ) )
51
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : Union[str, Any] , a__ : List[str]=None , a__ : Union[str, Any]=None , **a__ : Optional[Any] ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Any , a__ : Any=None , a__ : str=None , a__ : List[Any]=None , **a__ : List[str] ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : Optional[Any] , *a__ : int , **a__ : List[Any] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : Any , *a__ : Union[str, Any] , **a__ : Any ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
51
1
'''simple docstring''' import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version a__ : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt') def __snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : int = 16_000 ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = int(round(sample_rate * max_length ) ) if len(SCREAMING_SNAKE_CASE_ ) <= sample_length: return wav UpperCAmelCase = randint(0 , len(SCREAMING_SNAKE_CASE_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field(default=UpperCAmelCase_ , metadata={"help": "Name of a dataset from the datasets package"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "A file containing the training audio paths and labels."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "A file containing the validation audio paths and labels."} ) _lowerCamelCase =field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) _lowerCamelCase =field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) _lowerCamelCase =field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) _lowerCamelCase =field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) _lowerCamelCase =field( default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) _lowerCamelCase =field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Name or path of preprocessor config."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def __snake_case ( self : Union[str, Any] ): if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , a__ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def __snake_case ( ) -> int: """simple docstring""" UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCAmelCase = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE_ ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} " + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. UpperCAmelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. UpperCAmelCase = DatasetDict() UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--label_column_name` to the correct text column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy UpperCAmelCase = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. UpperCAmelCase = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) UpperCAmelCase = feature_extractor.model_input_names[0] def train_transforms(SCREAMING_SNAKE_CASE_ : int ): UpperCAmelCase = [] for audio in batch[data_args.audio_column_name]: UpperCAmelCase = random_subsample( audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(SCREAMING_SNAKE_CASE_ : List[Any] ): UpperCAmelCase = [audio['''array'''] for audio in batch[data_args.audio_column_name]] UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. UpperCAmelCase = raw_datasets['''train'''].features[data_args.label_column_name].names UpperCAmelCase, UpperCAmelCase = {}, {} for i, label in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCAmelCase = str(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = label # Load the accuracy metric from the datasets package UpperCAmelCase = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(SCREAMING_SNAKE_CASE_ : Dict ): UpperCAmelCase = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=SCREAMING_SNAKE_CASE_ , references=eval_pred.label_ids ) UpperCAmelCase = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(SCREAMING_SNAKE_CASE_ ) , labelaid=SCREAMING_SNAKE_CASE_ , idalabel=SCREAMING_SNAKE_CASE_ , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: UpperCAmelCase = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(SCREAMING_SNAKE_CASE_ , output_all_columns=SCREAMING_SNAKE_CASE_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: UpperCAmelCase = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(SCREAMING_SNAKE_CASE_ , output_all_columns=SCREAMING_SNAKE_CASE_ ) # Initialize our trainer UpperCAmelCase = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: UpperCAmelCase = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase = last_checkpoint UpperCAmelCase = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCAmelCase = trainer.evaluate() trainer.log_metrics('''eval''' , SCREAMING_SNAKE_CASE_ ) trainer.save_metrics('''eval''' , SCREAMING_SNAKE_CASE_ ) # Write model card and (optionally) push to hub UpperCAmelCase = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE_ ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
51
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
1
'''simple docstring''' import flax.linen as nn import jax import jax.numpy as jnp class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =jnp.floataa def __snake_case ( self : List[str] ): UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : List[Any] , a__ : int ): UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = hidden_states.shape UpperCAmelCase = jax.image.resize( a__ , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , ) UpperCAmelCase = self.conv(a__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =jnp.floataa def __snake_case ( self : List[Any] ): UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , a__ : Dict ): # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) UpperCAmelCase = self.conv(a__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =None _lowerCamelCase =0.0 _lowerCamelCase =None _lowerCamelCase =jnp.floataa def __snake_case ( self : Tuple ): UpperCAmelCase = self.in_channels if self.out_channels is None else self.out_channels UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Conv( a__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = nn.Dense(a__ , dtype=self.dtype ) UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Dropout(self.dropout_prob ) UpperCAmelCase = nn.Conv( a__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCAmelCase = None if use_nin_shortcut: UpperCAmelCase = nn.Conv( a__ , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , ) def __call__( self : Dict , a__ : Optional[Any] , a__ : int , a__ : Dict=True ): UpperCAmelCase = hidden_states UpperCAmelCase = self.norma(a__ ) UpperCAmelCase = nn.swish(a__ ) UpperCAmelCase = self.conva(a__ ) UpperCAmelCase = self.time_emb_proj(nn.swish(a__ ) ) UpperCAmelCase = jnp.expand_dims(jnp.expand_dims(a__ , 1 ) , 1 ) UpperCAmelCase = hidden_states + temb UpperCAmelCase = self.norma(a__ ) UpperCAmelCase = nn.swish(a__ ) UpperCAmelCase = self.dropout(a__ , a__ ) UpperCAmelCase = self.conva(a__ ) if self.conv_shortcut is not None: UpperCAmelCase = self.conv_shortcut(a__ ) return hidden_states + residual
51
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ): pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _lowerCamelCase =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ): UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __snake_case ( self : int , a__ : Dict , a__ : Tuple ): pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __snake_case ( self : str ): pass @slow @require_torch def __snake_case ( self : Optional[Any] ): UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __snake_case ( self : Dict ): UpperCAmelCase = '''facebook/sam-vit-huge''' UpperCAmelCase = pipeline('''mask-generation''' , model=a__ ) UpperCAmelCase = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, ] , )
51
1
'''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 a__ : Any = datasets.utils.logging.get_logger(__name__) a__ : str = ['names', 'prefix'] a__ : Any = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] a__ : Dict = ['encoding_errors', 'on_bad_lines'] a__ : Optional[Any] = ['date_format'] @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase ="," _lowerCamelCase =None _lowerCamelCase ="infer" _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =False _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =True _lowerCamelCase =None _lowerCamelCase ="." _lowerCamelCase =None _lowerCamelCase ='"' _lowerCamelCase =0 _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =True _lowerCamelCase =0 _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =None _lowerCamelCase =1_00_00 _lowerCamelCase =None _lowerCamelCase ="strict" _lowerCamelCase ="error" _lowerCamelCase =None def __snake_case ( self : Any ): if self.delimiter is not None: UpperCAmelCase = self.delimiter if self.column_names is not None: UpperCAmelCase = self.column_names @property def __snake_case ( self : Optional[Any] ): UpperCAmelCase = { '''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() , a__ ): 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 lowerCAmelCase__ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase =CsvConfig def __snake_case ( self : Optional[int] ): return datasets.DatasetInfo(features=self.config.features ) def __snake_case ( self : int , a__ : List[str] ): 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}" ) UpperCAmelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): UpperCAmelCase = data_files if isinstance(a__ , a__ ): UpperCAmelCase = [files] UpperCAmelCase = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] UpperCAmelCase = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): UpperCAmelCase = [files] UpperCAmelCase = [dl_manager.iter_files(a__ ) for file in files] splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={'''files''': files} ) ) return splits def __snake_case ( self : Any , a__ : pa.Table ): if self.config.features is not None: UpperCAmelCase = self.config.features.arrow_schema if all(not require_storage_cast(a__ ) for feature in self.config.features.values() ): # cheaper cast UpperCAmelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=a__ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCAmelCase = table_cast(a__ , a__ ) return pa_table def __snake_case ( self : Any , a__ : Tuple ): UpperCAmelCase = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCAmelCase = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(a__ ) 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(a__ ) ): UpperCAmelCase = pd.read_csv(a__ , iterator=a__ , dtype=a__ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(a__ ): UpperCAmelCase = pa.Table.from_pandas(a__ ) # 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(a__ ) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
51
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
1
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =VideoToVideoSDPipeline _lowerCamelCase =TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} _lowerCamelCase =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} _lowerCamelCase =PipelineTesterMixin.required_optional_params - {"latents"} _lowerCamelCase =False # No `output_type`. _lowerCamelCase =frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def __snake_case ( self : List[str] ): torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=a__ , set_alpha_to_one=a__ , ) torch.manual_seed(0 ) UpperCAmelCase = 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 ) UpperCAmelCase = 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 , ) UpperCAmelCase = CLIPTextModel(a__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) UpperCAmelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def __snake_case ( self : Any , a__ : int , a__ : int=0 ): # 3 frames UpperCAmelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def __snake_case ( self : Dict ): UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = VideoToVideoSDPipeline(**a__ ) UpperCAmelCase = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) UpperCAmelCase = self.get_dummy_inputs(a__ ) UpperCAmelCase = '''np''' UpperCAmelCase = sd_pipe(**a__ ).frames UpperCAmelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) UpperCAmelCase = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __snake_case ( self : Tuple ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a__ , expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __snake_case ( self : List[str] ): pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __snake_case ( self : Any ): pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def __snake_case ( self : str ): pass def __snake_case ( self : List[str] ): return super().test_progress_bar() @slow @skip_mps class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : List[str] ): UpperCAmelCase = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = torch.randn((1, 10, 3, 1024, 576) , generator=a__ ) UpperCAmelCase = video.to('''cuda''' ) UpperCAmelCase = '''Spiderman is surfing''' UpperCAmelCase = pipe(a__ , video=a__ , generator=a__ , num_inference_steps=3 , output_type='''pt''' ).frames UpperCAmelCase = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
51
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , a__ : List[str]="sayef/fsner-bert-base-uncased" ): super(a__ , self ).__init__() UpperCAmelCase = AutoModel.from_pretrained(a__ , return_dict=a__ ) UpperCAmelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCAmelCase = torch.nn.Softmax(dim=1 ) def __snake_case ( self : List[Any] , **a__ : Tuple ): return self.bert(**a__ ).last_hidden_state def __snake_case ( self : int , a__ : List[str] ): return token_embeddings.sum(2 , keepdim=a__ ) def __snake_case ( self : str , a__ : str , a__ : str , a__ : int=1 ): return self.softmax(T * self.cos(a__ , a__ ) ) def __snake_case ( self : Tuple , a__ : Tuple , a__ : str ): UpperCAmelCase = W_supports['''sizes'''].tolist() UpperCAmelCase = W_supports['''start_token_id'''].item() UpperCAmelCase = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = W_supports['''input_ids'''] == start_token_id UpperCAmelCase = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(a__ ): if i == 0: UpperCAmelCase = 0 else: UpperCAmelCase = support_sizes[i - 1] UpperCAmelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase = torch.vstack((p_starts, p_start) ) UpperCAmelCase = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase = p_start UpperCAmelCase = p_end return p_starts, p_ends
51
1
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path a__ : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) a__ : list[int] = [ord(letter) for letter in string.ascii_lowercase] a__ : set[int] = {ord(char) for char in VALID_CHARS} a__ : list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def __snake_case ( SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : tuple[int, ...] ) -> str | None: """simple docstring""" UpperCAmelCase = "" UpperCAmelCase = 42 UpperCAmelCase = 42 UpperCAmelCase = 42 for keychar, cipherchar in zip(cycle(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ): UpperCAmelCase = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(SCREAMING_SNAKE_CASE_ ) return decoded def __snake_case ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[str]: """simple docstring""" UpperCAmelCase = [] for key in product(SCREAMING_SNAKE_CASE_ , repeat=3 ): UpperCAmelCase = try_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if encoded is not None: possibles.append(SCREAMING_SNAKE_CASE_ ) return possibles def __snake_case ( SCREAMING_SNAKE_CASE_ : list[str] , SCREAMING_SNAKE_CASE_ : str ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def __snake_case ( SCREAMING_SNAKE_CASE_ : str = "p059_cipher.txt" ) -> int: """simple docstring""" UpperCAmelCase = 42 UpperCAmelCase = 42 UpperCAmelCase = 42 UpperCAmelCase = 42 UpperCAmelCase = Path(SCREAMING_SNAKE_CASE_ ).parent.joinpath(SCREAMING_SNAKE_CASE_ ).read_text(encoding='''utf-8''' ) UpperCAmelCase = [int(SCREAMING_SNAKE_CASE_ ) for number in data.strip().split(''',''' )] UpperCAmelCase = filter_valid_chars(SCREAMING_SNAKE_CASE_ ) for common_word in COMMON_WORDS: UpperCAmelCase = filter_common_word(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) == 1: break UpperCAmelCase = possibles[0] return sum(ord(SCREAMING_SNAKE_CASE_ ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
51
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
1
'''simple docstring''' from math import factorial def __snake_case ( SCREAMING_SNAKE_CASE_ : int = 100 ) -> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
51
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
1
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =CTRLTokenizer _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : List[str] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCAmelCase = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] UpperCAmelCase = dict(zip(a__ , range(len(a__ ) ) ) ) UpperCAmelCase = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] UpperCAmelCase = {'''unk_token''': '''<unk>'''} UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(a__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(a__ ) ) def __snake_case ( self : Union[str, Any] , **a__ : int ): kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **a__ ) def __snake_case ( self : List[str] , a__ : List[Any] ): UpperCAmelCase = '''adapt react readapt apt''' UpperCAmelCase = '''adapt react readapt apt''' return input_text, output_text def __snake_case ( self : int ): UpperCAmelCase = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase = '''adapt react readapt apt''' UpperCAmelCase = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() UpperCAmelCase = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = tokens + [tokenizer.unk_token] UpperCAmelCase = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ )
51
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" print('''Loading config file...''' ) def flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" , SCREAMING_SNAKE_CASE_ : Dict="." ): UpperCAmelCase = [] for k, v in d.items(): UpperCAmelCase = parent_key + sep + k if parent_key else k if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sep=SCREAMING_SNAKE_CASE_ ).items() ) else: items.append((new_key, v) ) return dict(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = argparse.Namespace() with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as yaml_file: try: UpperCAmelCase = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=yaml.FullLoader ) UpperCAmelCase = flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ ) for k, v in flat_cfg.items(): setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) ) return config def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase = MobileViTVaConfig() UpperCAmelCase = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase = 151 UpperCAmelCase = 512 UpperCAmelCase = '''ade20k-id2label.json''' UpperCAmelCase = True elif task_name.startswith('''voc_''' ): UpperCAmelCase = 21 UpperCAmelCase = 512 UpperCAmelCase = '''pascal-voc-id2label.json''' UpperCAmelCase = True # orig_config UpperCAmelCase = load_orig_config_file(SCREAMING_SNAKE_CASE_ ) assert getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" UpperCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = val def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str=False ) -> int: """simple docstring""" if base_model: UpperCAmelCase = '''''' else: UpperCAmelCase = '''mobilevitv2.''' UpperCAmelCase = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase = k[8:] else: UpperCAmelCase = k if ".block." in k: UpperCAmelCase = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase = k_new.replace('''conv_1.''' , f"{model_prefix}conv_stem." ) for i in [1, 2]: if f"layer_{i}." in k: UpperCAmelCase = k_new.replace(f"layer_{i}." , f"{model_prefix}encoder.layer.{i-1}.layer." ) if ".exp_1x1." in k: UpperCAmelCase = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f"layer_{i}.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.0." , f"{model_prefix}encoder.layer.{i-1}.downsampling_layer." ) if f"layer_{i}.1.local_rep.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.0." , f"{model_prefix}encoder.layer.{i-1}.conv_kxk." ) if f"layer_{i}.1.local_rep.1." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.1." , f"{model_prefix}encoder.layer.{i-1}.conv_1x1." ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase = [0, 1] elif i == 4: UpperCAmelCase = [0, 1, 2, 3] elif i == 5: UpperCAmelCase = [0, 1, 2] for j in j_in: if f"layer_{i}.1.global_rep.{j}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j}." , f"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." ) if f"layer_{i}.1.global_rep.{j+1}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j+1}." , f"{model_prefix}encoder.layer.{i-1}.layernorm." ) if f"layer_{i}.1.conv_proj." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.conv_proj." , f"{model_prefix}encoder.layer.{i-1}.conv_projection." ) if "pre_norm_attn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> int: """simple docstring""" UpperCAmelCase = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(SCREAMING_SNAKE_CASE_ ) for k in keys_to_ignore: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> List[Any]: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = get_mobilevitva_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False else: UpperCAmelCase = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False # remove and rename some keys of load the original model UpperCAmelCase = checkpoint remove_unused_keys(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load modified state_dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase = outputs.logits UpperCAmelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {task_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 __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
51
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Tuple = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="dpt" def __init__( self : Optional[int] , a__ : int=768 , a__ : List[Any]=12 , a__ : Union[str, Any]=12 , a__ : List[str]=3072 , a__ : Optional[int]="gelu" , a__ : List[Any]=0.0 , a__ : List[str]=0.0 , a__ : Dict=0.02 , a__ : Optional[int]=1e-1_2 , a__ : Any=384 , a__ : List[str]=16 , a__ : Tuple=3 , a__ : int=False , a__ : List[Any]=True , a__ : Any=[2, 5, 8, 11] , a__ : Any="project" , a__ : Any=[4, 2, 1, 0.5] , a__ : Union[str, Any]=[96, 192, 384, 768] , a__ : Dict=256 , a__ : Dict=-1 , a__ : str=False , a__ : Union[str, Any]=True , a__ : Optional[Any]=0.4 , a__ : Union[str, Any]=255 , a__ : int=0.1 , a__ : str=[1, 1024, 24, 24] , a__ : str=[0, 1] , a__ : Union[str, Any]=None , **a__ : str , ): super().__init__(**a__ ) UpperCAmelCase = hidden_size UpperCAmelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('''Initializing the config with a `BiT` backbone.''' ) UpperCAmelCase = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, } UpperCAmelCase = BitConfig(**a__ ) elif isinstance(a__ , a__ ): logger.info('''Initializing the config with a `BiT` backbone.''' ) UpperCAmelCase = BitConfig(**a__ ) elif isinstance(a__ , a__ ): UpperCAmelCase = backbone_config else: raise ValueError( f"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) UpperCAmelCase = backbone_featmap_shape UpperCAmelCase = neck_ignore_stages if readout_type != "project": raise ValueError('''Readout type must be \'project\' when using `DPT-hybrid` mode.''' ) else: UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = [] UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = qkv_bias UpperCAmelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('''Readout_type must be one of [\'ignore\', \'add\', \'project\']''' ) UpperCAmelCase = readout_type UpperCAmelCase = reassemble_factors UpperCAmelCase = neck_hidden_sizes UpperCAmelCase = fusion_hidden_size UpperCAmelCase = head_in_index UpperCAmelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) UpperCAmelCase = use_auxiliary_head UpperCAmelCase = auxiliary_loss_weight UpperCAmelCase = semantic_loss_ignore_index UpperCAmelCase = semantic_classifier_dropout def __snake_case ( self : List[str] ): UpperCAmelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCAmelCase = self.backbone_config.to_dict() UpperCAmelCase = self.__class__.model_type return output
51
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="megatron-bert" def __init__( self : Dict , a__ : Union[str, Any]=29056 , a__ : Dict=1024 , a__ : str=24 , a__ : Any=16 , a__ : Tuple=4096 , a__ : Optional[int]="gelu" , a__ : Tuple=0.1 , a__ : Tuple=0.1 , a__ : Any=512 , a__ : Optional[Any]=2 , a__ : str=0.02 , a__ : Optional[int]=1e-1_2 , a__ : Union[str, Any]=0 , a__ : Optional[Any]="absolute" , a__ : Dict=True , **a__ : Dict , ): super().__init__(pad_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache
51
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a__ : Dict = { 'configuration_mobilenet_v2': [ 'MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileNetV2Config', 'MobileNetV2OnnxConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = ['MobileNetV2FeatureExtractor'] a__ : List[str] = ['MobileNetV2ImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileNetV2ForImageClassification', 'MobileNetV2ForSemanticSegmentation', 'MobileNetV2Model', 'MobileNetV2PreTrainedModel', 'load_tf_weights_in_mobilenet_v2', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
'''simple docstring''' from __future__ import annotations a__ : List[str] = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , a__ : dict[str, list[str]] , a__ : str ): UpperCAmelCase = graph # mapping node to its parent in resulting breadth first tree UpperCAmelCase = {} UpperCAmelCase = source_vertex def __snake_case ( self : Optional[int] ): UpperCAmelCase = {self.source_vertex} UpperCAmelCase = None UpperCAmelCase = [self.source_vertex] # first in first out queue while queue: UpperCAmelCase = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(a__ ) UpperCAmelCase = vertex queue.append(a__ ) def __snake_case ( self : Any , a__ : str ): if target_vertex == self.source_vertex: return self.source_vertex UpperCAmelCase = self.parent.get(a__ ) if target_vertex_parent is None: UpperCAmelCase = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(a__ ) return self.shortest_path(a__ ) + f"->{target_vertex}" if __name__ == "__main__": a__ : Tuple = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
51
1
'''simple docstring''' from __future__ import annotations def __snake_case ( SCREAMING_SNAKE_CASE_ : list[int] ) -> bool: """simple docstring""" return len(set(SCREAMING_SNAKE_CASE_ ) ) == len(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : Tuple = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys a__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('''repo_id''' , ['''canonical_dataset_name''', '''org-name/dataset-name'''] ) @pytest.mark.parametrize('''path''' , ['''filename.csv''', '''filename with blanks.csv'''] ) @pytest.mark.parametrize('''revision''' , [None, '''v2'''] ) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase = hf_hub_url(repo_id=SCREAMING_SNAKE_CASE_ , path=SCREAMING_SNAKE_CASE_ , revision=SCREAMING_SNAKE_CASE_ ) assert url == f"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(SCREAMING_SNAKE_CASE_ )}"
51
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Any = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : list[list[int]] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] ) -> bool: """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def __snake_case ( SCREAMING_SNAKE_CASE_ : list[list[int]] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" 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 UpperCAmelCase = next_ver # Validate created path if util_hamilton_cycle(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , curr_ind + 1 ): return True # Backtrack UpperCAmelCase = -1 return False def __snake_case ( SCREAMING_SNAKE_CASE_ : list[list[int]] , SCREAMING_SNAKE_CASE_ : int = 0 ) -> list[int]: """simple docstring""" UpperCAmelCase = [-1] * (len(SCREAMING_SNAKE_CASE_ ) + 1) # initialize start and end of path with starting index UpperCAmelCase = UpperCAmelCase = 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 []
51
'''simple docstring''' from math import factorial def __snake_case ( SCREAMING_SNAKE_CASE_ : int = 100 ) -> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
51
1
'''simple docstring''' import math class lowerCAmelCase__ : '''simple docstring''' def __snake_case ( self : List[Any] , a__ : list[list[float]] , a__ : list[int] ): UpperCAmelCase = 0.0 UpperCAmelCase = 0.0 for i in range(len(a__ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def __snake_case ( self : Union[str, Any] , a__ : list[list[int | float]] , a__ : list[int] , a__ : int , a__ : float ): for i in range(len(a__ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def __snake_case ( ) -> None: """simple docstring""" UpperCAmelCase = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCAmelCase = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCAmelCase = SelfOrganizingMap() UpperCAmelCase = 3 UpperCAmelCase = 0.5 for _ in range(SCREAMING_SNAKE_CASE_ ): for j in range(len(SCREAMING_SNAKE_CASE_ ) ): # training sample UpperCAmelCase = training_samples[j] # Compute the winning vector UpperCAmelCase = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Update the winning vector UpperCAmelCase = self_organizing_map.update(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # classify test sample UpperCAmelCase = [0, 0, 0, 1] UpperCAmelCase = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # results print(f"Clusters that the test sample belongs to : {winner}" ) print(f"Weights that have been trained : {weights}" ) # running the main() function if __name__ == "__main__": main()
51
'''simple docstring''' import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =StableUnCLIPPipeline _lowerCamelCase =TEXT_TO_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _lowerCamelCase =False def __snake_case ( self : str ): UpperCAmelCase = 32 UpperCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=a__ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) UpperCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=a__ , num_layers=1 , ) torch.manual_seed(0 ) UpperCAmelCase = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1000 , clip_sample=a__ , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) UpperCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=a__ ) UpperCAmelCase = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=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 , ) ) torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a__ , layers_per_block=1 , upcast_attention=a__ , use_linear_projection=a__ , ) torch.manual_seed(0 ) UpperCAmelCase = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=a__ , steps_offset=1 , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL() UpperCAmelCase = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def __snake_case ( self : str , a__ : Dict , a__ : List[str]=0 ): if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __snake_case ( self : List[Any] ): UpperCAmelCase = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=a__ ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[int] ): UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = pipe('''anime turle''' , generator=a__ , output_type='''np''' ) UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ ) def __snake_case ( self : str ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
51
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None ) -> Union[str, Any]: """simple docstring""" if subparsers is not None: UpperCAmelCase = subparsers.add_parser('''test''' ) else: UpperCAmelCase = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=SCREAMING_SNAKE_CASE_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE_ ) return parser def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: UpperCAmelCase = script_name else: UpperCAmelCase = f"--config_file={args.config_file} {script_name}" UpperCAmelCase = ['''accelerate-launch'''] + test_args.split() UpperCAmelCase = execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = test_command_parser() UpperCAmelCase = parser.parse_args() test_command(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
51
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" if not head: return True # split the list to two parts UpperCAmelCase, UpperCAmelCase = head.next, head while fast and fast.next: UpperCAmelCase = fast.next.next UpperCAmelCase = slow.next UpperCAmelCase = slow.next UpperCAmelCase = None # Don't forget here! But forget still works! # reverse the second part UpperCAmelCase = None while second: UpperCAmelCase = second.next UpperCAmelCase = node UpperCAmelCase = second UpperCAmelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False UpperCAmelCase = node.next UpperCAmelCase = head.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Union[str, Any]: """simple docstring""" if not head or not head.next: return True # 1. Get the midpoint (slow) UpperCAmelCase = UpperCAmelCase = UpperCAmelCase = head while fast and fast.next: UpperCAmelCase, UpperCAmelCase = fast.next.next, slow.next # 2. Push the second half into the stack UpperCAmelCase = [slow.val] while slow.next: UpperCAmelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False UpperCAmelCase = cur.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Tuple: """simple docstring""" if not head or not head.next: return True UpperCAmelCase = {} UpperCAmelCase = 0 while head: if head.val in d: d[head.val].append(SCREAMING_SNAKE_CASE_ ) else: UpperCAmelCase = [pos] UpperCAmelCase = head.next pos += 1 UpperCAmelCase = pos - 1 UpperCAmelCase = 0 for v in d.values(): if len(SCREAMING_SNAKE_CASE_ ) % 2 != 0: middle += 1 else: UpperCAmelCase = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): if v[i] + v[len(SCREAMING_SNAKE_CASE_ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
51
1
'''simple docstring''' from __future__ import annotations def __snake_case ( SCREAMING_SNAKE_CASE_ : list[int] ) -> int: """simple docstring""" UpperCAmelCase = len(SCREAMING_SNAKE_CASE_ ) // 2 # choose the middle 3 elements UpperCAmelCase = 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()
51
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Tuple , a__ : List[Any]=None , a__ : str=None , **a__ : Tuple ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Optional[Any] , a__ : Optional[int]=None , a__ : List[str]=None , a__ : int=None , **a__ : Tuple ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : List[str] , *a__ : Union[str, Any] , **a__ : Optional[int] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : int , *a__ : Optional[int] , **a__ : int ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __snake_case ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a__ , ) return self.image_processor_class @property def __snake_case ( self : List[Any] ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a__ , ) return self.image_processor
51
1
'''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: a__ : List[str] = None a__ : Tuple = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} a__ : Optional[int] = { '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', }, } a__ : str = { 'camembert-base': 512, } a__ : Union[str, Any] = '▁' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =VOCAB_FILES_NAMES _lowerCamelCase =PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase =["input_ids", "attention_mask"] _lowerCamelCase =CamembertTokenizer def __init__( self : Optional[Any] , a__ : Optional[int]=None , a__ : List[Any]=None , a__ : int="<s>" , a__ : List[str]="</s>" , a__ : int="</s>" , a__ : int="<s>" , a__ : Optional[int]="<unk>" , a__ : List[Any]="<pad>" , a__ : Tuple="<mask>" , a__ : Dict=["<s>NOTUSED", "</s>NOTUSED"] , **a__ : Optional[int] , ): # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase = 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__ , ) UpperCAmelCase = vocab_file UpperCAmelCase = False if not self.vocab_file else True def __snake_case ( self : List[Any] , a__ : List[int] , a__ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase = [self.cls_token_id] UpperCAmelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __snake_case ( self : List[str] , a__ : List[int] , a__ : Optional[List[int]] = None ): UpperCAmelCase = [self.sep_token_id] UpperCAmelCase = [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 __snake_case ( self : Tuple , a__ : str , a__ : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(a__ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCAmelCase = 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,)
51
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =XGLMTokenizer _lowerCamelCase =XGLMTokenizerFast _lowerCamelCase =True _lowerCamelCase =True def __snake_case ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[Any] ): UpperCAmelCase = '''<pad>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(a__ ) , 1008 ) def __snake_case ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(a__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( a__ , [ 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''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ 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 __snake_case ( self : Optional[Any] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def __snake_case ( self : Optional[int] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=a__ ) UpperCAmelCase = pickle.dumps(a__ ) pickle.loads(a__ ) def __snake_case ( self : Tuple ): if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = '''I was born in 92000, and this is falsé.''' UpperCAmelCase = tokenizer.tokenize(a__ ) UpperCAmelCase = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = tokenizer.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __snake_case ( self : int ): UpperCAmelCase = '''Hello World!''' UpperCAmelCase = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : List[str] ): UpperCAmelCase = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off UpperCAmelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : Any ): # fmt: off UpperCAmelCase = { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name='''facebook/xglm-564M''' , padding=a__ , )
51
1
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : str = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> YolosConfig: """simple docstring""" UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 UpperCAmelCase = [800, 1_333] UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase = 330 UpperCAmelCase = 14 UpperCAmelCase = 6 UpperCAmelCase = 1_320 elif "yolos_s" in yolos_name: UpperCAmelCase = 384 UpperCAmelCase = 1_536 UpperCAmelCase = 12 UpperCAmelCase = 6 elif "yolos_b" in yolos_name: UpperCAmelCase = [800, 1_344] UpperCAmelCase = 91 UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''coco-detection-id2label.json''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosConfig , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[: config.hidden_size, :] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if "backbone" in name: UpperCAmelCase = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: UpperCAmelCase = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: UpperCAmelCase = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: UpperCAmelCase = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: UpperCAmelCase = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCAmelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: UpperCAmelCase = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCAmelCase = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCAmelCase = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCAmelCase = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCAmelCase = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCAmelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCAmelCase = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: UpperCAmelCase = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: UpperCAmelCase = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: UpperCAmelCase = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: UpperCAmelCase = key.split('''.''' ) UpperCAmelCase = int(key_split[2] ) UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase = val[:dim, :] UpperCAmelCase = val[ dim : dim * 2, : ] UpperCAmelCase = val[-dim:, :] else: UpperCAmelCase = val[:dim] UpperCAmelCase = val[dim : dim * 2] UpperCAmelCase = val[-dim:] else: UpperCAmelCase = val return orig_state_dict def __snake_case ( ) -> torch.Tensor: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" UpperCAmelCase = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' )['''model'''] # load 🤗 model UpperCAmelCase = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCAmelCase = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase = 800 if yolos_name != '''yolos_ti''' else 512 UpperCAmelCase = YolosImageProcessor(format='''coco_detection''' , size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase, UpperCAmelCase = outputs.logits, outputs.pred_boxes UpperCAmelCase, UpperCAmelCase = None, None if yolos_name == "yolos_ti": UpperCAmelCase = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) UpperCAmelCase = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) UpperCAmelCase = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) UpperCAmelCase = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": UpperCAmelCase = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) UpperCAmelCase = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {yolos_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: UpperCAmelCase = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) model.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.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.' ) a__ : Optional[Any] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
51
1
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING a__ : Optional[int] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Dict , *a__ : Optional[Any] , **a__ : List[Any] ): super().__init__(*a__ , **a__ ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def __snake_case ( self : int , a__ : Union[str, Any]=None ): UpperCAmelCase = {} if top_k is not None: UpperCAmelCase = top_k return {}, {}, postprocess_params def __call__( self : Any , a__ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a__ : List[str] ): return super().__call__(a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : Dict ): UpperCAmelCase = load_image(a__ ) UpperCAmelCase = self.image_processor(images=a__ , return_tensors=self.framework ) return model_inputs def __snake_case ( self : str , a__ : Optional[Any] ): UpperCAmelCase = self.model(**a__ ) return model_outputs def __snake_case ( self : Union[str, Any] , a__ : Tuple , a__ : Union[str, Any]=5 ): if top_k > self.model.config.num_labels: UpperCAmelCase = self.model.config.num_labels if self.framework == "pt": UpperCAmelCase = model_outputs.logits.softmax(-1 )[0] UpperCAmelCase, UpperCAmelCase = probs.topk(a__ ) elif self.framework == "tf": UpperCAmelCase = stable_softmax(model_outputs.logits , axis=-1 )[0] UpperCAmelCase = tf.math.top_k(a__ , k=a__ ) UpperCAmelCase, UpperCAmelCase = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f"Unsupported framework: {self.framework}" ) UpperCAmelCase = scores.tolist() UpperCAmelCase = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a__ , a__ )]
51
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a__ : List[Any] = logging.get_logger(__name__) a__ : int = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a__ : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] a__ : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="whisper" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[Any] , a__ : Any=51865 , a__ : Any=80 , a__ : Dict=6 , a__ : int=4 , a__ : int=6 , a__ : str=4 , a__ : int=1536 , a__ : Optional[Any]=1536 , a__ : str=0.0 , a__ : Optional[int]=0.0 , a__ : Optional[int]=50257 , a__ : int=True , a__ : Optional[int]=True , a__ : str="gelu" , a__ : List[str]=256 , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Any=0.0 , a__ : str=0.02 , a__ : str=False , a__ : int=1500 , a__ : Tuple=448 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Tuple=None , a__ : List[Any]=[220, 50256] , a__ : Optional[int]=False , a__ : Optional[Any]=256 , a__ : Any=False , a__ : int=0.05 , a__ : Optional[Any]=10 , a__ : Dict=2 , a__ : Optional[Any]=0.0 , a__ : Tuple=10 , a__ : Any=0 , a__ : str=7 , **a__ : Any , ): UpperCAmelCase = vocab_size UpperCAmelCase = num_mel_bins UpperCAmelCase = d_model UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size UpperCAmelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks UpperCAmelCase = median_filter_width super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , suppress_tokens=a__ , begin_suppress_tokens=a__ , **a__ , ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : List[str] ): UpperCAmelCase = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: UpperCAmelCase = {0: '''batch'''} else: UpperCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs def __snake_case ( self : str , a__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a__ : int = -1 , a__ : int = -1 , a__ : bool = False , a__ : Optional["TensorType"] = None , a__ : int = 22050 , a__ : float = 5.0 , a__ : int = 220 , ): UpperCAmelCase = OrderedDict() UpperCAmelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a__ , framework=a__ , sampling_rate=a__ , time_duration=a__ , frequency=a__ , ) UpperCAmelCase = encoder_inputs['''input_features'''].shape[2] UpperCAmelCase = encoder_sequence_length // 2 if self.use_past else seq_length UpperCAmelCase = super().generate_dummy_inputs( preprocessor.tokenizer , a__ , a__ , a__ , a__ ) UpperCAmelCase = encoder_inputs.pop('''input_features''' ) UpperCAmelCase = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: UpperCAmelCase = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __snake_case ( self : Dict ): return 1e-3
51
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , a__ : Optional[Any] , a__ : Any=13 , a__ : str=3 , a__ : List[Any]=224 , a__ : Any=30 , a__ : List[Any]=400 , a__ : Optional[int]=True , a__ : str=None , a__ : Dict=True , a__ : Tuple=[0.5, 0.5, 0.5] , a__ : List[str]=[0.5, 0.5, 0.5] , ): UpperCAmelCase = size if size is not None else {'''height''': 18, '''width''': 18} UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std def __snake_case ( self : List[str] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =ViTImageProcessor if is_vision_available() else None def __snake_case ( self : int ): UpperCAmelCase = EfficientFormerImageProcessorTester(self ) @property def __snake_case ( self : Optional[int] ): return self.image_proc_tester.prepare_image_processor_dict() def __snake_case ( self : Tuple ): UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a__ , '''image_mean''' ) ) self.assertTrue(hasattr(a__ , '''image_std''' ) ) self.assertTrue(hasattr(a__ , '''do_normalize''' ) ) self.assertTrue(hasattr(a__ , '''do_resize''' ) ) self.assertTrue(hasattr(a__ , '''size''' ) ) def __snake_case ( self : Optional[int] ): pass def __snake_case ( self : List[str] ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ ) for image in image_inputs: self.assertIsInstance(a__ , Image.Image ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __snake_case ( self : int ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ , numpify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , np.ndarray ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __snake_case ( self : List[Any] ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ , torchify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
51
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =LEDConfig _lowerCamelCase ={} _lowerCamelCase ="gelu" def __init__( self : Tuple , a__ : Any , a__ : int=13 , a__ : List[Any]=7 , a__ : int=True , a__ : Union[str, Any]=False , a__ : Tuple=99 , a__ : Any=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : List[Any]=37 , a__ : List[Any]=0.1 , a__ : Any=0.1 , a__ : Optional[int]=20 , a__ : List[Any]=2 , a__ : Union[str, Any]=1 , a__ : List[Any]=0 , a__ : Union[str, Any]=4 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after UpperCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests UpperCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) UpperCAmelCase = prepare_led_inputs_dict(a__ , a__ , a__ ) UpperCAmelCase = tf.concat( [tf.zeros_like(a__ )[:, :-1], tf.ones_like(a__ )[:, -1:]] , axis=-1 , ) UpperCAmelCase = global_attention_mask return config, inputs_dict def __snake_case ( self : Optional[int] , a__ : List[str] , a__ : int ): UpperCAmelCase = TFLEDModel(config=a__ ).get_decoder() UpperCAmelCase = inputs_dict['''input_ids'''] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(a__ , attention_mask=a__ , use_cache=a__ ) UpperCAmelCase, UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(a__ , attention_mask=a__ )[0] UpperCAmelCase = model(a__ , attention_mask=a__ , past_key_values=a__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(a__ , a__ , rtol=1e-3 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=None , ) -> Dict: """simple docstring""" if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowerCamelCase =(TFLEDForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase =( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : Optional[Any] ): UpperCAmelCase = TFLEDModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ ) def __snake_case ( self : int ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = tf.zeros_like(inputs_dict['''attention_mask'''] ) UpperCAmelCase = 2 UpperCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) UpperCAmelCase = True UpperCAmelCase = self.model_tester.seq_length UpperCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(a__ : Tuple ): UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(a__ : int ): UpperCAmelCase = [t.numpy() for t in outputs.encoder_attentions] UpperCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = len(a__ ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) if self.is_encoder_decoder: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_decoder_attentions_output(a__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) ) self.assertEqual(model.config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __snake_case ( self : Any ): pass def __snake_case ( self : Union[str, Any] ): # TODO: Head-masking not yet implement pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> Tuple: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE_ , dtype=tf.intaa ) a__ : int = 1e-4 @slow @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, 768) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 ) def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 , rtol=1e-3 )
51
1
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : List[Any] = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : List[Any] , a__ : str ): with open(a__ , encoding='''utf-8''' ) as input_file: UpperCAmelCase = re.compile(R'''(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)''' ) UpperCAmelCase = input_file.read() UpperCAmelCase = regexp.search(a__ ) return match def __snake_case ( self : Any , a__ : str ): with open(a__ , encoding='''utf-8''' ) as input_file: UpperCAmelCase = re.compile(R'''#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()''' , re.DOTALL ) UpperCAmelCase = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` UpperCAmelCase = regexp.finditer(a__ ) UpperCAmelCase = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def __snake_case ( self : Optional[Any] ): UpperCAmelCase = Path('''./datasets''' ) UpperCAmelCase = list(dataset_paths.absolute().glob('''**/*.py''' ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(a__ ) ): raise AssertionError(f"open(...) must use utf-8 encoding in {dataset}" ) def __snake_case ( self : int ): UpperCAmelCase = Path('''./datasets''' ) UpperCAmelCase = list(dataset_paths.absolute().glob('''**/*.py''' ) ) for dataset in dataset_files: if self._no_print_statements(str(a__ ) ): raise AssertionError(f"print statement found in {dataset}. Use datasets.logger/logging instead." )
51
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : Optional[int] = { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="speech_to_text" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Dict , a__ : Any=10000 , a__ : Union[str, Any]=12 , a__ : List[str]=2048 , a__ : List[Any]=4 , a__ : Optional[Any]=6 , a__ : Dict=2048 , a__ : Optional[int]=4 , a__ : Dict=0.0 , a__ : List[str]=0.0 , a__ : Dict=True , a__ : str=True , a__ : Tuple="relu" , a__ : str=256 , a__ : Tuple=0.1 , a__ : Tuple=0.0 , a__ : List[str]=0.0 , a__ : Dict=0.02 , a__ : List[Any]=2 , a__ : Union[str, Any]=True , a__ : Optional[Any]=1 , a__ : Tuple=0 , a__ : Optional[int]=2 , a__ : List[str]=6000 , a__ : List[str]=1024 , a__ : Dict=2 , a__ : int=(5, 5) , a__ : Union[str, Any]=1024 , a__ : Optional[Any]=80 , a__ : Tuple=1 , **a__ : Optional[int] , ): UpperCAmelCase = vocab_size UpperCAmelCase = d_model UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions UpperCAmelCase = num_conv_layers UpperCAmelCase = list(a__ ) UpperCAmelCase = conv_channels UpperCAmelCase = input_feat_per_channel UpperCAmelCase = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` ''' f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, " f"`config.num_conv_layers = {self.num_conv_layers}`." ) super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , **a__ , )
51
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : Union[str, Any] , a__ : List[str]=None , a__ : Union[str, Any]=None , **a__ : Optional[Any] ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Any , a__ : Any=None , a__ : str=None , a__ : List[Any]=None , **a__ : List[str] ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : Optional[Any] , *a__ : int , **a__ : List[Any] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : Any , *a__ : Union[str, Any] , **a__ : Any ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
51
1
'''simple docstring''' import qiskit def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> qiskit.result.counts.Counts: """simple docstring""" UpperCAmelCase = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register UpperCAmelCase = qiskit.QuantumCircuit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator UpperCAmelCase = qiskit.execute(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , shots=1_000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
51
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
1
'''simple docstring''' import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Dict ): UpperCAmelCase = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(a__ ) ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(a__ ) ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(a__ ) ) def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(a__ ) ) def __snake_case ( self : Dict ): UpperCAmelCase = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(a__ ) ) def __snake_case ( self : Tuple ): UpperCAmelCase = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertTrue(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : Tuple ): UpperCAmelCase = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertTrue(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : Any ): # pass variant but use the non-variant filenames UpperCAmelCase = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertTrue(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] UpperCAmelCase = '''fp16''' self.assertFalse(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : List[str] ): UpperCAmelCase = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertTrue(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : str ): # pass variant but use the non-variant filenames UpperCAmelCase = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertTrue(is_safetensors_compatible(a__ , variant=a__ ) ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] UpperCAmelCase = '''fp16''' self.assertFalse(is_safetensors_compatible(a__ , variant=a__ ) )
51
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ): pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _lowerCamelCase =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ): UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __snake_case ( self : int , a__ : Dict , a__ : Tuple ): pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __snake_case ( self : str ): pass @slow @require_torch def __snake_case ( self : Optional[Any] ): UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __snake_case ( self : Dict ): UpperCAmelCase = '''facebook/sam-vit-huge''' UpperCAmelCase = pipeline('''mask-generation''' , model=a__ ) UpperCAmelCase = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, ] , )
51
1
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Any=1_000 ) -> Any: """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd UpperCAmelCase = n - 1 UpperCAmelCase = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) UpperCAmelCase = 0 while count < prec: UpperCAmelCase = random.randint(2 , n - 1 ) UpperCAmelCase = bin_exp_mod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if b != 1: UpperCAmelCase = True for _ in range(SCREAMING_SNAKE_CASE_ ): if b == n - 1: UpperCAmelCase = False break UpperCAmelCase = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": a__ : List[Any] = abs(int(input('Enter bound : ').strip())) print('Here\'s the list of primes:') print(', '.join(str(i) for i in range(n + 1) if is_prime_big(i)))
51
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
1
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def __snake_case ( ) -> None: """simple docstring""" assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
51
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , a__ : List[str]="sayef/fsner-bert-base-uncased" ): super(a__ , self ).__init__() UpperCAmelCase = AutoModel.from_pretrained(a__ , return_dict=a__ ) UpperCAmelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCAmelCase = torch.nn.Softmax(dim=1 ) def __snake_case ( self : List[Any] , **a__ : Tuple ): return self.bert(**a__ ).last_hidden_state def __snake_case ( self : int , a__ : List[str] ): return token_embeddings.sum(2 , keepdim=a__ ) def __snake_case ( self : str , a__ : str , a__ : str , a__ : int=1 ): return self.softmax(T * self.cos(a__ , a__ ) ) def __snake_case ( self : Tuple , a__ : Tuple , a__ : str ): UpperCAmelCase = W_supports['''sizes'''].tolist() UpperCAmelCase = W_supports['''start_token_id'''].item() UpperCAmelCase = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = W_supports['''input_ids'''] == start_token_id UpperCAmelCase = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(a__ ): if i == 0: UpperCAmelCase = 0 else: UpperCAmelCase = support_sizes[i - 1] UpperCAmelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase = torch.vstack((p_starts, p_start) ) UpperCAmelCase = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase = p_start UpperCAmelCase = p_end return p_starts, p_ends
51
1
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , a__ : int , a__ : int , a__ : float = 0 ): UpperCAmelCase, UpperCAmelCase = row, column UpperCAmelCase = [[default_value for c in range(a__ )] for r in range(a__ )] def __str__( self : int ): UpperCAmelCase = f"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier UpperCAmelCase = 0 for row_vector in self.array: for obj in row_vector: UpperCAmelCase = max(a__ , len(str(a__ ) ) ) UpperCAmelCase = f"%{max_element_length}s" # Make string and return def single_line(a__ : list[float] ) -> str: nonlocal string_format_identifier UpperCAmelCase = '''[''' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(a__ ) for row_vector in self.array ) return s def __repr__( self : Optional[Any] ): return str(self ) def __snake_case ( self : Dict , a__ : tuple[int, int] ): if not (isinstance(a__ , (list, tuple) ) and len(a__ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , a__ : tuple[int, int] ): assert self.validate_indicies(a__ ) return self.array[loc[0]][loc[1]] def __setitem__( self : Dict , a__ : tuple[int, int] , a__ : float ): assert self.validate_indicies(a__ ) UpperCAmelCase = value def __add__( self : int , a__ : Matrix ): assert isinstance(a__ , a__ ) assert self.row == another.row and self.column == another.column # Add UpperCAmelCase = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase = self[r, c] + another[r, c] return result def __neg__( self : List[Any] ): UpperCAmelCase = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase = -self[r, c] return result def __sub__( self : List[str] , a__ : Matrix ): return self + (-another) def __mul__( self : Any , a__ : int | float | Matrix ): if isinstance(a__ , (int, float) ): # Scalar multiplication UpperCAmelCase = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase = self[r, c] * another return result elif isinstance(a__ , a__ ): # Matrix multiplication assert self.column == another.row UpperCAmelCase = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: UpperCAmelCase = f"Unsupported type given for another ({type(a__ )})" raise TypeError(a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase = self[r, c] return result def __snake_case ( self : Optional[Any] , a__ : Matrix , a__ : Matrix ): assert isinstance(a__ , a__ ) and isinstance(a__ , a__ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate UpperCAmelCase = v.transpose() UpperCAmelCase = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ) -> None: """simple docstring""" UpperCAmelCase = Matrix(3 , 3 , 0 ) for i in range(3 ): UpperCAmelCase = 1 print(f"a^(-1) is {ainv}" ) # u, v UpperCAmelCase = Matrix(3 , 1 , 0 ) UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = 1, 2, -3 UpperCAmelCase = Matrix(3 , 1 , 0 ) UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = 4, -2, 5 print(f"u is {u}" ) print(f"v is {v}" ) print(f"uv^T is {u * v.transpose()}" ) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}" ) def __snake_case ( ) -> None: """simple docstring""" import doctest doctest.testmod() testa()
51
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
1
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar a__ : Optional[Any] = TypeVar('KEY') a__ : List[str] = TypeVar('VAL') @dataclass(frozen=UpperCAmelCase_ , slots=UpperCAmelCase_ ) class lowerCAmelCase__ ( Generic[KEY, VAL] ): '''simple docstring''' _lowerCamelCase =42 _lowerCamelCase =42 class lowerCAmelCase__ ( _Item ): '''simple docstring''' def __init__( self : Dict ): super().__init__(a__ , a__ ) def __bool__( self : str ): return False a__ : List[Any] = _DeletedItem() class lowerCAmelCase__ ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , a__ : int = 8 , a__ : float = 0.75 ): UpperCAmelCase = initial_block_size UpperCAmelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 UpperCAmelCase = capacity_factor UpperCAmelCase = 0 def __snake_case ( self : Dict , a__ : KEY ): return hash(a__ ) % len(self._buckets ) def __snake_case ( self : Optional[Any] , a__ : int ): return (ind + 1) % len(self._buckets ) def __snake_case ( self : Any , a__ : int , a__ : KEY , a__ : VAL ): UpperCAmelCase = self._buckets[ind] if not stored: UpperCAmelCase = _Item(a__ , a__ ) self._len += 1 return True elif stored.key == key: UpperCAmelCase = _Item(a__ , a__ ) return True else: return False def __snake_case ( self : Tuple ): UpperCAmelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(a__ ) def __snake_case ( self : Any ): if len(self._buckets ) <= self._initial_block_size: return False UpperCAmelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __snake_case ( self : List[Any] , a__ : int ): UpperCAmelCase = self._buckets UpperCAmelCase = [None] * new_size UpperCAmelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __snake_case ( self : Optional[int] ): self._resize(len(self._buckets ) * 2 ) def __snake_case ( self : Union[str, Any] ): self._resize(len(self._buckets ) // 2 ) def __snake_case ( self : Dict , a__ : KEY ): UpperCAmelCase = self._get_bucket_index(a__ ) for _ in range(len(self._buckets ) ): yield ind UpperCAmelCase = self._get_next_ind(a__ ) def __snake_case ( self : Union[str, Any] , a__ : KEY , a__ : VAL ): for ind in self._iterate_buckets(a__ ): if self._try_set(a__ , a__ , a__ ): break def __setitem__( self : Union[str, Any] , a__ : KEY , a__ : VAL ): if self._is_full(): self._size_up() self._add_item(a__ , a__ ) def __delitem__( self : Optional[int] , a__ : KEY ): for ind in self._iterate_buckets(a__ ): UpperCAmelCase = self._buckets[ind] if item is None: raise KeyError(a__ ) if item is _deleted: continue if item.key == key: UpperCAmelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : int , a__ : KEY ): for ind in self._iterate_buckets(a__ ): UpperCAmelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(a__ ) def __len__( self : str ): return self._len def __iter__( self : int ): yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[Any] ): UpperCAmelCase = ''' ,'''.join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
51
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Dict = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="roformer" def __init__( self : Dict , a__ : Any=50000 , a__ : Union[str, Any]=None , a__ : int=768 , a__ : Dict=12 , a__ : Dict=12 , a__ : Tuple=3072 , a__ : Dict="gelu" , a__ : Union[str, Any]=0.1 , a__ : List[str]=0.1 , a__ : Any=1536 , a__ : Optional[Any]=2 , a__ : int=0.02 , a__ : Dict=1e-1_2 , a__ : Optional[int]=0 , a__ : Optional[int]=False , a__ : Dict=True , **a__ : Any , ): super().__init__(pad_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size if embedding_size is None else embedding_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = rotary_value UpperCAmelCase = use_cache class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : int ): if self.task == "multiple-choice": UpperCAmelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCAmelCase = {0: '''batch''', 1: '''sequence'''} UpperCAmelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
51
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" print('''Loading config file...''' ) def flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" , SCREAMING_SNAKE_CASE_ : Dict="." ): UpperCAmelCase = [] for k, v in d.items(): UpperCAmelCase = parent_key + sep + k if parent_key else k if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sep=SCREAMING_SNAKE_CASE_ ).items() ) else: items.append((new_key, v) ) return dict(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = argparse.Namespace() with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as yaml_file: try: UpperCAmelCase = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=yaml.FullLoader ) UpperCAmelCase = flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ ) for k, v in flat_cfg.items(): setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) ) return config def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase = MobileViTVaConfig() UpperCAmelCase = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase = 151 UpperCAmelCase = 512 UpperCAmelCase = '''ade20k-id2label.json''' UpperCAmelCase = True elif task_name.startswith('''voc_''' ): UpperCAmelCase = 21 UpperCAmelCase = 512 UpperCAmelCase = '''pascal-voc-id2label.json''' UpperCAmelCase = True # orig_config UpperCAmelCase = load_orig_config_file(SCREAMING_SNAKE_CASE_ ) assert getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" UpperCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = val def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str=False ) -> int: """simple docstring""" if base_model: UpperCAmelCase = '''''' else: UpperCAmelCase = '''mobilevitv2.''' UpperCAmelCase = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase = k[8:] else: UpperCAmelCase = k if ".block." in k: UpperCAmelCase = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase = k_new.replace('''conv_1.''' , f"{model_prefix}conv_stem." ) for i in [1, 2]: if f"layer_{i}." in k: UpperCAmelCase = k_new.replace(f"layer_{i}." , f"{model_prefix}encoder.layer.{i-1}.layer." ) if ".exp_1x1." in k: UpperCAmelCase = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f"layer_{i}.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.0." , f"{model_prefix}encoder.layer.{i-1}.downsampling_layer." ) if f"layer_{i}.1.local_rep.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.0." , f"{model_prefix}encoder.layer.{i-1}.conv_kxk." ) if f"layer_{i}.1.local_rep.1." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.1." , f"{model_prefix}encoder.layer.{i-1}.conv_1x1." ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase = [0, 1] elif i == 4: UpperCAmelCase = [0, 1, 2, 3] elif i == 5: UpperCAmelCase = [0, 1, 2] for j in j_in: if f"layer_{i}.1.global_rep.{j}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j}." , f"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." ) if f"layer_{i}.1.global_rep.{j+1}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j+1}." , f"{model_prefix}encoder.layer.{i-1}.layernorm." ) if f"layer_{i}.1.conv_proj." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.conv_proj." , f"{model_prefix}encoder.layer.{i-1}.conv_projection." ) if "pre_norm_attn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> int: """simple docstring""" UpperCAmelCase = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(SCREAMING_SNAKE_CASE_ ) for k in keys_to_ignore: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> List[Any]: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = get_mobilevitva_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False else: UpperCAmelCase = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False # remove and rename some keys of load the original model UpperCAmelCase = checkpoint remove_unused_keys(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load modified state_dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase = outputs.logits UpperCAmelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {task_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 __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
51
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Any = logging.get_logger(__name__) a__ : Optional[Any] = { 'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="altclip_text_model" def __init__( self : Any , a__ : Dict=250002 , a__ : int=1024 , a__ : Tuple=24 , a__ : Union[str, Any]=16 , a__ : List[Any]=4096 , a__ : Union[str, Any]="gelu" , a__ : Optional[Any]=0.1 , a__ : Any=0.1 , a__ : List[Any]=514 , a__ : str=1 , a__ : Tuple=0.02 , a__ : Optional[Any]=0.02 , a__ : int=1e-0_5 , a__ : str=1 , a__ : Tuple=0 , a__ : List[Any]=2 , a__ : List[str]="absolute" , a__ : Union[str, Any]=True , a__ : int=768 , **a__ : str , ): super().__init__(pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = initializer_factor UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache UpperCAmelCase = project_dim class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="altclip_vision_model" def __init__( self : Dict , a__ : Tuple=768 , a__ : Dict=3072 , a__ : Any=512 , a__ : Any=12 , a__ : List[Any]=12 , a__ : int=3 , a__ : Dict=224 , a__ : Any=32 , a__ : Tuple="quick_gelu" , a__ : Tuple=1e-5 , a__ : Optional[int]=0.0 , a__ : List[Any]=0.02 , a__ : List[Any]=1.0 , **a__ : Dict , ): super().__init__(**a__ ) UpperCAmelCase = hidden_size UpperCAmelCase = intermediate_size UpperCAmelCase = projection_dim UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = num_channels UpperCAmelCase = patch_size UpperCAmelCase = image_size UpperCAmelCase = initializer_range UpperCAmelCase = initializer_factor UpperCAmelCase = attention_dropout UpperCAmelCase = layer_norm_eps UpperCAmelCase = hidden_act @classmethod def __snake_case ( cls : Tuple , a__ : Union[str, os.PathLike] , **a__ : Optional[int] ): cls._set_token_in_kwargs(a__ ) UpperCAmelCase, UpperCAmelCase = cls.get_config_dict(a__ , **a__ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('''model_type''' ) == "altclip": UpperCAmelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(a__ , **a__ ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="altclip" _lowerCamelCase =True def __init__( self : Optional[Any] , a__ : List[Any]=None , a__ : Any=None , a__ : Optional[Any]=768 , a__ : List[Any]=2.6_592 , **a__ : str ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). UpperCAmelCase = kwargs.pop('''text_config_dict''' , a__ ) UpperCAmelCase = kwargs.pop('''vision_config_dict''' , a__ ) super().__init__(**a__ ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: UpperCAmelCase = {} # This is the complete result when using `text_config_dict`. UpperCAmelCase = AltCLIPTextConfig(**a__ ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: UpperCAmelCase = ( f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. " f"The value `text_config_dict[\"{key}\"]` will be used instead." ) # If inferred from default argument values (just to be super careful) else: UpperCAmelCase = ( f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The " f"value `text_config[\"{key}\"]` will be overriden." ) logger.warning(a__ ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: UpperCAmelCase = {} # This is the complete result when using `vision_config_dict`. UpperCAmelCase = AltCLIPVisionConfig(**a__ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: UpperCAmelCase = { str(a__ ): value for key, value in _vision_config_dict['''id2label'''].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: UpperCAmelCase = ( f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different " f"values. The value `vision_config_dict[\"{key}\"]` will be used instead." ) # If inferred from default argument values (just to be super careful) else: UpperCAmelCase = ( f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. " f"The value `vision_config[\"{key}\"]` will be overriden." ) logger.warning(a__ ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: UpperCAmelCase = {} logger.info('''`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.''' ) if vision_config is None: UpperCAmelCase = {} logger.info('''`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.''' ) UpperCAmelCase = AltCLIPTextConfig(**a__ ) UpperCAmelCase = AltCLIPVisionConfig(**a__ ) UpperCAmelCase = projection_dim UpperCAmelCase = logit_scale_init_value UpperCAmelCase = 1.0 @classmethod def __snake_case ( cls : int , a__ : AltCLIPTextConfig , a__ : AltCLIPVisionConfig , **a__ : Any ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__ ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = copy.deepcopy(self.__dict__ ) UpperCAmelCase = self.text_config.to_dict() UpperCAmelCase = self.vision_config.to_dict() UpperCAmelCase = self.__class__.model_type return output
51
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="megatron-bert" def __init__( self : Dict , a__ : Union[str, Any]=29056 , a__ : Dict=1024 , a__ : str=24 , a__ : Any=16 , a__ : Tuple=4096 , a__ : Optional[int]="gelu" , a__ : Tuple=0.1 , a__ : Tuple=0.1 , a__ : Any=512 , a__ : Optional[Any]=2 , a__ : str=0.02 , a__ : Optional[int]=1e-1_2 , a__ : Union[str, Any]=0 , a__ : Optional[Any]="absolute" , a__ : Dict=True , **a__ : Dict , ): super().__init__(pad_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache
51
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : int ): UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = BlipImageProcessor() UpperCAmelCase = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-BertModel''' ) UpperCAmelCase = BlipProcessor(a__ , a__ ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Dict , **a__ : Dict ): return AutoProcessor.from_pretrained(self.tmpdirname , **a__ ).tokenizer def __snake_case ( self : Dict , **a__ : List[str] ): return AutoProcessor.from_pretrained(self.tmpdirname , **a__ ).image_processor def __snake_case ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Tuple ): UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] UpperCAmelCase = [Image.fromarray(np.moveaxis(a__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[str] ): UpperCAmelCase = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) UpperCAmelCase = self.get_image_processor(do_normalize=a__ , padding_value=1.0 ) UpperCAmelCase = BlipProcessor.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.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.get_image_processor() UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = BlipProcessor(tokenizer=a__ , image_processor=a__ ) UpperCAmelCase = self.prepare_image_inputs() UpperCAmelCase = image_processor(a__ , return_tensors='''np''' ) UpperCAmelCase = processor(images=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 __snake_case ( self : Any ): UpperCAmelCase = self.get_image_processor() UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = BlipProcessor(tokenizer=a__ , image_processor=a__ ) UpperCAmelCase = '''lower newer''' UpperCAmelCase = processor(text=a__ ) UpperCAmelCase = tokenizer(a__ , return_token_type_ids=a__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __snake_case ( self : str ): UpperCAmelCase = self.get_image_processor() UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = BlipProcessor(tokenizer=a__ , image_processor=a__ ) UpperCAmelCase = '''lower newer''' UpperCAmelCase = self.prepare_image_inputs() UpperCAmelCase = processor(text=a__ , images=a__ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''input_ids''', '''attention_mask'''] ) # test if it raises when no input is passed with pytest.raises(a__ ): processor() def __snake_case ( self : List[str] ): UpperCAmelCase = self.get_image_processor() UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = BlipProcessor(tokenizer=a__ , image_processor=a__ ) UpperCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCAmelCase = processor.batch_decode(a__ ) UpperCAmelCase = tokenizer.batch_decode(a__ ) self.assertListEqual(a__ , a__ ) def __snake_case ( self : int ): UpperCAmelCase = self.get_image_processor() UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = BlipProcessor(tokenizer=a__ , image_processor=a__ ) UpperCAmelCase = '''lower newer''' UpperCAmelCase = self.prepare_image_inputs() UpperCAmelCase = processor(text=a__ , images=a__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''input_ids''', '''attention_mask'''] )
51
'''simple docstring''' from __future__ import annotations a__ : List[str] = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , a__ : dict[str, list[str]] , a__ : str ): UpperCAmelCase = graph # mapping node to its parent in resulting breadth first tree UpperCAmelCase = {} UpperCAmelCase = source_vertex def __snake_case ( self : Optional[int] ): UpperCAmelCase = {self.source_vertex} UpperCAmelCase = None UpperCAmelCase = [self.source_vertex] # first in first out queue while queue: UpperCAmelCase = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(a__ ) UpperCAmelCase = vertex queue.append(a__ ) def __snake_case ( self : Any , a__ : str ): if target_vertex == self.source_vertex: return self.source_vertex UpperCAmelCase = self.parent.get(a__ ) if target_vertex_parent is None: UpperCAmelCase = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(a__ ) return self.shortest_path(a__ ) + f"->{target_vertex}" if __name__ == "__main__": a__ : Tuple = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
51
1
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : list ) -> int: """simple docstring""" if not grid or not grid[0]: raise TypeError('''The grid does not contain the appropriate information''' ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] UpperCAmelCase = grid[0] for row_n in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): UpperCAmelCase = grid[row_n] UpperCAmelCase = fill_row(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = grid[row_n] return grid[-1][-1] def __snake_case ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list ) -> list: """simple docstring""" current_row[0] += row_above[0] for cell_n in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
51
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : Tuple = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys a__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
51
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Any = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
1
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType SCREAMING_SNAKE_CASE__ : List[Any] = get_logger(__name__) def __lowercase ( snake_case, snake_case, snake_case, snake_case, snake_case=0 ): """simple docstring""" os.makedirs(snake_case, exist_ok=snake_case ) with FSDP.state_dict_type( snake_case, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): __magic_name__ :Tuple = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __magic_name__ :List[Any] = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' __magic_name__ :int = os.path.join(snake_case, snake_case ) if accelerator.process_index == 0: logger.info(f'''Saving model to {output_model_file}''' ) torch.save(snake_case, snake_case ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __magic_name__ :Optional[int] = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __magic_name__ :List[Any] = os.path.join(snake_case, snake_case ) logger.info(f'''Saving model to {output_model_file}''' ) torch.save(snake_case, snake_case ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __magic_name__ :Optional[Any] = os.path.join(snake_case, f'''{MODEL_NAME}_{model_index}''' ) os.makedirs(snake_case, exist_ok=snake_case ) logger.info(f'''Saving model to {ckpt_dir}''' ) __magic_name__ :List[Any] = {'''model''': state_dict} dist_cp.save_state_dict( state_dict=snake_case, storage_writer=dist_cp.FileSystemWriter(snake_case ), planner=DefaultSavePlanner(), ) logger.info(f'''Model saved to {ckpt_dir}''' ) def __lowercase ( snake_case, snake_case, snake_case, snake_case, snake_case=0 ): """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( '''Set the `sync_module_states` flag to `True` so that model states are synced across processes when ''' '''initializing FSDP object''' ) return __magic_name__ :List[Any] = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' __magic_name__ :Any = os.path.join(snake_case, snake_case ) logger.info(f'''Loading model from {input_model_file}''' ) __magic_name__ :Any = torch.load(snake_case ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __magic_name__ :Union[str, Any] = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __magic_name__ :Tuple = os.path.join(snake_case, snake_case ) logger.info(f'''Loading model from {input_model_file}''' ) __magic_name__ :List[Any] = torch.load(snake_case ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __magic_name__ :Tuple = ( os.path.join(snake_case, f'''{MODEL_NAME}_{model_index}''' ) if f'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading model from {ckpt_dir}''' ) __magic_name__ :Any = {'''model''': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case, storage_reader=dist_cp.FileSystemReader(snake_case ), planner=DefaultLoadPlanner(), ) __magic_name__ :Any = state_dict['''model'''] logger.info(f'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(snake_case ) def __lowercase ( snake_case, snake_case, snake_case, snake_case, snake_case, snake_case=0 ): """simple docstring""" os.makedirs(snake_case, exist_ok=snake_case ) with FSDP.state_dict_type( snake_case, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): __magic_name__ :List[Any] = FSDP.optim_state_dict(snake_case, snake_case ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __magic_name__ :Optional[int] = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __magic_name__ :str = os.path.join(snake_case, snake_case ) logger.info(f'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(snake_case, snake_case ) logger.info(f'''Optimizer state saved in {output_optimizer_file}''' ) else: __magic_name__ :Tuple = os.path.join(snake_case, f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(snake_case, exist_ok=snake_case ) logger.info(f'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={'''optimizer''': optim_state}, storage_writer=dist_cp.FileSystemWriter(snake_case ), planner=DefaultSavePlanner(), ) logger.info(f'''Optimizer state saved in {ckpt_dir}''' ) def __lowercase ( snake_case, snake_case, snake_case, snake_case, snake_case, snake_case=0 ): """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __magic_name__ :Tuple = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __magic_name__ :Optional[Any] = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __magic_name__ :str = os.path.join(snake_case, snake_case ) logger.info(f'''Loading Optimizer state from {input_optimizer_file}''' ) __magic_name__ :Optional[int] = torch.load(snake_case ) logger.info(f'''Optimizer state loaded from {input_optimizer_file}''' ) else: __magic_name__ :Tuple = ( os.path.join(snake_case, f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if f'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading Optimizer from {ckpt_dir}''' ) __magic_name__ :List[str] = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict(), optimizer_key='''optimizer''', storage_reader=dist_cp.FileSystemReader(snake_case ), ) __magic_name__ :str = optim_state['''optimizer'''] logger.info(f'''Optimizer loaded from {ckpt_dir}''' ) __magic_name__ :Tuple = FSDP.optim_state_dict_to_load(snake_case, snake_case, snake_case ) optimizer.load_state_dict(snake_case )
0
'''simple docstring''' from math import factorial def __snake_case ( SCREAMING_SNAKE_CASE_ : int = 100 ) -> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
51
0
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _A ( _lowercase ) -> Tuple: """simple docstring""" monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set() ) @pytest.fixture def _A ( _lowercase ) -> int: """simple docstring""" class __lowerCamelCase : def __init__( self: Optional[Any],A_: Tuple ): '''simple docstring''' __UpperCamelCase = metric_id class __lowerCamelCase : _lowercase = [MetricMock(_a ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def snake_case_ ( self: Any ): '''simple docstring''' return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock() ) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))] ) def _A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) -> str: """simple docstring""" if "tmp_path" in args: __UpperCamelCase = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args ) with pytest.warns(_lowercase , match='https://huggingface.co/docs/evaluate' ): func(*_lowercase )
1
'''simple docstring''' import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =StableUnCLIPPipeline _lowerCamelCase =TEXT_TO_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _lowerCamelCase =False def __snake_case ( self : str ): UpperCAmelCase = 32 UpperCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=a__ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) UpperCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=a__ , num_layers=1 , ) torch.manual_seed(0 ) UpperCAmelCase = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1000 , clip_sample=a__ , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) UpperCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=a__ ) UpperCAmelCase = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=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 , ) ) torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a__ , layers_per_block=1 , upcast_attention=a__ , use_linear_projection=a__ , ) torch.manual_seed(0 ) UpperCAmelCase = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=a__ , steps_offset=1 , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL() UpperCAmelCase = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def __snake_case ( self : str , a__ : Dict , a__ : List[str]=0 ): if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __snake_case ( self : List[Any] ): UpperCAmelCase = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=a__ ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[int] ): UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = pipe('''anime turle''' , generator=a__ , output_type='''np''' ) UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ ) def __snake_case ( self : str ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
51
0
import logging import os from .state import PartialState class lowerCamelCase__ ( logging.LoggerAdapter): """simple docstring""" @staticmethod def snake_case_ ( __lowerCAmelCase : Optional[int] ) -> Dict: _A = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def snake_case_ ( self : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Dict , *__lowerCAmelCase : str , **__lowerCAmelCase : Any ) -> str: if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) _A = kwargs.pop('''main_process_only''' , __lowerCAmelCase ) _A = kwargs.pop('''in_order''' , __lowerCAmelCase ) if self.isEnabledFor(__lowerCAmelCase ): if self._should_log(__lowerCAmelCase ): _A , _A = self.process(__lowerCAmelCase , __lowerCAmelCase ) self.logger.log(__lowerCAmelCase , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ) elif in_order: _A = PartialState() for i in range(state.num_processes ): if i == state.process_index: _A , _A = self.process(__lowerCAmelCase , __lowerCAmelCase ) self.logger.log(__lowerCAmelCase , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ) state.wait_for_everyone() def SCREAMING_SNAKE_CASE_ ( _snake_case :str , _snake_case :str = None ) -> int: if log_level is None: _A = os.environ.get('''ACCELERATE_LOG_LEVEL''' , _snake_case ) _A = logging.getLogger(_snake_case ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(_snake_case , {} )
2
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" if not head: return True # split the list to two parts UpperCAmelCase, UpperCAmelCase = head.next, head while fast and fast.next: UpperCAmelCase = fast.next.next UpperCAmelCase = slow.next UpperCAmelCase = slow.next UpperCAmelCase = None # Don't forget here! But forget still works! # reverse the second part UpperCAmelCase = None while second: UpperCAmelCase = second.next UpperCAmelCase = node UpperCAmelCase = second UpperCAmelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False UpperCAmelCase = node.next UpperCAmelCase = head.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Union[str, Any]: """simple docstring""" if not head or not head.next: return True # 1. Get the midpoint (slow) UpperCAmelCase = UpperCAmelCase = UpperCAmelCase = head while fast and fast.next: UpperCAmelCase, UpperCAmelCase = fast.next.next, slow.next # 2. Push the second half into the stack UpperCAmelCase = [slow.val] while slow.next: UpperCAmelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False UpperCAmelCase = cur.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Tuple: """simple docstring""" if not head or not head.next: return True UpperCAmelCase = {} UpperCAmelCase = 0 while head: if head.val in d: d[head.val].append(SCREAMING_SNAKE_CASE_ ) else: UpperCAmelCase = [pos] UpperCAmelCase = head.next pos += 1 UpperCAmelCase = pos - 1 UpperCAmelCase = 0 for v in d.values(): if len(SCREAMING_SNAKE_CASE_ ) % 2 != 0: middle += 1 else: UpperCAmelCase = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): if v[i] + v[len(SCREAMING_SNAKE_CASE_ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
51
0
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def A_( A : Any , A : List[Any]): UpperCamelCase = int(A) assert noofclusters < len(A) # Find out the dimensionality UpperCamelCase = len(vectors[0]) # Will help select random centroids from among the available vectors UpperCamelCase = list(range(len(A))) shuffle(A) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. UpperCamelCase = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION UpperCamelCase = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points UpperCamelCase = [ tf.Variable(vectors[vector_indices[i]]) for i in range(A) ] ##These nodes will assign the centroid Variables the appropriate ##values UpperCamelCase = tf.placeholder('float64' , [dim]) UpperCamelCase = [] for centroid in centroids: cent_assigns.append(tf.assign(A , A)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) UpperCamelCase = [tf.Variable(0) for i in range(len(A))] ##These nodes will assign an assignment Variable the appropriate ##value UpperCamelCase = tf.placeholder('int32') UpperCamelCase = [] for assignment in assignments: cluster_assigns.append(tf.assign(A , A)) ##Now lets construct the node that will compute the mean # The placeholder for the input UpperCamelCase = tf.placeholder('float' , [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors UpperCamelCase = tf.reduce_mean(A , 0) ##Node for computing Euclidean distances # Placeholders for input UpperCamelCase = tf.placeholder('float' , [dim]) UpperCamelCase = tf.placeholder('float' , [dim]) UpperCamelCase = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(A , A) , 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input UpperCamelCase = tf.placeholder('float' , [noofclusters]) UpperCamelCase = tf.argmin(A , 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. UpperCamelCase = tf.initialize_all_variables() # Initialize all variables sess.run(A) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. UpperCamelCase = 100 for _ in range(A): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(A)): UpperCamelCase = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. UpperCamelCase = [ sess.run(A , feed_dict={va: vect, va: sess.run(A)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input UpperCamelCase = sess.run( A , feed_dict={centroid_distances: distances}) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment}) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(A): # Collect all the vectors assigned to this cluster UpperCamelCase = [ vectors[i] for i in range(len(A)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location UpperCamelCase = sess.run( A , feed_dict={mean_input: array(A)}) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location}) # Return centroids and assignments UpperCamelCase = sess.run(A) UpperCamelCase = sess.run(A) return centroids, assignments
3
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Tuple , a__ : List[Any]=None , a__ : str=None , **a__ : Tuple ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Optional[Any] , a__ : Optional[int]=None , a__ : List[str]=None , a__ : int=None , **a__ : Tuple ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : List[str] , *a__ : Union[str, Any] , **a__ : Optional[int] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : int , *a__ : Optional[int] , **a__ : int ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __snake_case ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a__ , ) return self.image_processor_class @property def __snake_case ( self : List[Any] ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a__ , ) return self.image_processor
51
0
"""simple docstring""" import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __UpperCamelCase : Tuple = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) __UpperCamelCase : Union[str, Any] = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } __UpperCamelCase : Dict = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : Any = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Extra Ignored Subsection''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], } ], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } __UpperCamelCase : int = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : Dict = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) __UpperCamelCase : int = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : int = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) __UpperCamelCase : Tuple = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : int = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' __UpperCamelCase : List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : Optional[Any] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).''' __UpperCamelCase : int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' __UpperCamelCase : Optional[Any] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' __UpperCamelCase : Any = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' __UpperCamelCase : Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' __UpperCamelCase : Optional[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' __UpperCamelCase : int = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' __UpperCamelCase : str = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : str = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' __UpperCamelCase : Optional[int] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' __UpperCamelCase : Union[str, Any] = '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.''' __UpperCamelCase : str = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : List[Any] = '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.''' __UpperCamelCase : Tuple = '''''' __UpperCamelCase : Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' __UpperCamelCase : List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' __UpperCamelCase : Optional[Any] = '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.''' @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Any , _UpperCAmelCase : Optional[int] ): assert ReadMe.from_string(_UpperCAmelCase , _UpperCAmelCase ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : List[str] , _UpperCAmelCase : Dict ): with pytest.raises(_UpperCAmelCase , match=re.escape(expected_error.format(path='root' ) ) ): lowerCAmelCase = ReadMe.from_string(_UpperCAmelCase , _UpperCAmelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[str] ): with pytest.raises(_UpperCAmelCase , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(_UpperCAmelCase , _UpperCAmelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int ): ReadMe.from_string(_UpperCAmelCase , _UpperCAmelCase , suppress_parsing_errors=_UpperCAmelCase ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : List[str] , _UpperCAmelCase : Tuple ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = Path(_UpperCAmelCase ) / 'README.md' with open(_UpperCAmelCase , 'w+' ) as readme_file: readme_file.write(_UpperCAmelCase ) lowerCAmelCase = ReadMe.from_readme(_UpperCAmelCase , _UpperCAmelCase ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : List[Any] , _UpperCAmelCase : int ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = Path(_UpperCAmelCase ) / 'README.md' with open(_UpperCAmelCase , 'w+' ) as readme_file: readme_file.write(_UpperCAmelCase ) lowerCAmelCase = expected_error.format(path=_UpperCAmelCase ) with pytest.raises(_UpperCAmelCase , match=re.escape(_UpperCAmelCase ) ): lowerCAmelCase = ReadMe.from_readme(_UpperCAmelCase , _UpperCAmelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Tuple , _UpperCAmelCase : Any ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = Path(_UpperCAmelCase ) / 'README.md' with open(_UpperCAmelCase , 'w+' ) as readme_file: readme_file.write(_UpperCAmelCase ) lowerCAmelCase = expected_error.format(path=_UpperCAmelCase ) with pytest.raises(_UpperCAmelCase , match=re.escape(_UpperCAmelCase ) ): ReadMe.from_readme(_UpperCAmelCase , _UpperCAmelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[int] ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = Path(_UpperCAmelCase ) / 'README.md' with open(_UpperCAmelCase , 'w+' ) as readme_file: readme_file.write(_UpperCAmelCase ) ReadMe.from_readme(_UpperCAmelCase , _UpperCAmelCase , suppress_parsing_errors=_UpperCAmelCase )
4
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =XGLMTokenizer _lowerCamelCase =XGLMTokenizerFast _lowerCamelCase =True _lowerCamelCase =True def __snake_case ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[Any] ): UpperCAmelCase = '''<pad>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(a__ ) , 1008 ) def __snake_case ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(a__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( a__ , [ 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''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ 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 __snake_case ( self : Optional[Any] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def __snake_case ( self : Optional[int] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=a__ ) UpperCAmelCase = pickle.dumps(a__ ) pickle.loads(a__ ) def __snake_case ( self : Tuple ): if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = '''I was born in 92000, and this is falsé.''' UpperCAmelCase = tokenizer.tokenize(a__ ) UpperCAmelCase = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = tokenizer.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __snake_case ( self : int ): UpperCAmelCase = '''Hello World!''' UpperCAmelCase = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : List[str] ): UpperCAmelCase = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off UpperCAmelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : Any ): # fmt: off UpperCAmelCase = { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name='''facebook/xglm-564M''' , padding=a__ , )
51
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { """asapp/sew-tiny-100k""": """https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json""", # See all SEW models at https://huggingface.co/models?filter=sew } class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : Optional[int] = '''sew''' def __init__( self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3_072 , _lowercase=2 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , _lowercase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _lowercase=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=0 , _lowercase=1 , _lowercase=2 , **_lowercase , ): """simple docstring""" super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) _lowerCAmelCase = hidden_size _lowerCAmelCase = feat_extract_norm _lowerCAmelCase = feat_extract_activation _lowerCAmelCase = list(_lowercase ) _lowerCAmelCase = list(_lowercase ) _lowerCAmelCase = list(_lowercase ) _lowerCAmelCase = conv_bias _lowerCAmelCase = num_conv_pos_embeddings _lowerCAmelCase = num_conv_pos_embedding_groups _lowerCAmelCase = len(self.conv_dim ) _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = intermediate_size _lowerCAmelCase = squeeze_factor _lowerCAmelCase = hidden_act _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = activation_dropout _lowerCAmelCase = feat_proj_dropout _lowerCAmelCase = final_dropout _lowerCAmelCase = layerdrop _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range _lowerCAmelCase = vocab_size 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 _lowerCAmelCase = apply_spec_augment _lowerCAmelCase = mask_time_prob _lowerCAmelCase = mask_time_length _lowerCAmelCase = mask_time_min_masks _lowerCAmelCase = mask_feature_prob _lowerCAmelCase = mask_feature_length _lowerCAmelCase = mask_feature_min_masks # ctc loss _lowerCAmelCase = ctc_loss_reduction _lowerCAmelCase = ctc_zero_infinity # sequence classification _lowerCAmelCase = use_weighted_layer_sum _lowerCAmelCase = classifier_proj_size @property def _lowercase ( self ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
5
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : str = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> YolosConfig: """simple docstring""" UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 UpperCAmelCase = [800, 1_333] UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase = 330 UpperCAmelCase = 14 UpperCAmelCase = 6 UpperCAmelCase = 1_320 elif "yolos_s" in yolos_name: UpperCAmelCase = 384 UpperCAmelCase = 1_536 UpperCAmelCase = 12 UpperCAmelCase = 6 elif "yolos_b" in yolos_name: UpperCAmelCase = [800, 1_344] UpperCAmelCase = 91 UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''coco-detection-id2label.json''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosConfig , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[: config.hidden_size, :] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if "backbone" in name: UpperCAmelCase = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: UpperCAmelCase = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: UpperCAmelCase = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: UpperCAmelCase = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: UpperCAmelCase = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCAmelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: UpperCAmelCase = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCAmelCase = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCAmelCase = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCAmelCase = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCAmelCase = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCAmelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCAmelCase = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: UpperCAmelCase = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: UpperCAmelCase = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: UpperCAmelCase = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: UpperCAmelCase = key.split('''.''' ) UpperCAmelCase = int(key_split[2] ) UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase = val[:dim, :] UpperCAmelCase = val[ dim : dim * 2, : ] UpperCAmelCase = val[-dim:, :] else: UpperCAmelCase = val[:dim] UpperCAmelCase = val[dim : dim * 2] UpperCAmelCase = val[-dim:] else: UpperCAmelCase = val return orig_state_dict def __snake_case ( ) -> torch.Tensor: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" UpperCAmelCase = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' )['''model'''] # load 🤗 model UpperCAmelCase = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCAmelCase = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase = 800 if yolos_name != '''yolos_ti''' else 512 UpperCAmelCase = YolosImageProcessor(format='''coco_detection''' , size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase, UpperCAmelCase = outputs.logits, outputs.pred_boxes UpperCAmelCase, UpperCAmelCase = None, None if yolos_name == "yolos_ti": UpperCAmelCase = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) UpperCAmelCase = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) UpperCAmelCase = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) UpperCAmelCase = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": UpperCAmelCase = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) UpperCAmelCase = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {yolos_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: UpperCAmelCase = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) model.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.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.' ) a__ : Optional[Any] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
51
0
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): return 1 / (1 + np.exp(-z )) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Tuple ): return (-y * np.log(UpperCamelCase__ ) - (1 - y) * np.log(1 - h )).mean() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) return np.sum(y * scores - np.log(1 + np.exp(UpperCamelCase__ ) ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any]=70_000 ): SCREAMING_SNAKE_CASE__ = np.zeros(x.shape[1] ) for iterations in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sigmoid_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.dot(x.T , h - y ) / y.size SCREAMING_SNAKE_CASE__ = theta - alpha * gradient # updating the weights SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sigmoid_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cost_function(UpperCamelCase__ , UpperCamelCase__ ) if iterations % 100 == 0: print(f'''loss: {j} \t''' ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": _lowerCamelCase = datasets.load_iris() _lowerCamelCase = iris.data[:, :2] _lowerCamelCase = (iris.target != 0) * 1 _lowerCamelCase = 0.1 _lowerCamelCase = logistic_reg(alpha, x, y, max_iterations=70000) print('theta: ', theta) # printing the theta i.e our weights vector def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): return sigmoid_function( np.dot(UpperCamelCase__ , UpperCamelCase__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='b', label='0') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='r', label='1') ((_lowerCamelCase) , (_lowerCamelCase)) = (x[:, 0].min(), x[:, 0].max()) ((_lowerCamelCase) , (_lowerCamelCase)) = (x[:, 1].min(), x[:, 1].max()) ((_lowerCamelCase) , (_lowerCamelCase)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) _lowerCamelCase = np.c_[xxa.ravel(), xxa.ravel()] _lowerCamelCase = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='black') plt.legend() plt.show()
6
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a__ : List[Any] = logging.get_logger(__name__) a__ : int = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a__ : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] a__ : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="whisper" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[Any] , a__ : Any=51865 , a__ : Any=80 , a__ : Dict=6 , a__ : int=4 , a__ : int=6 , a__ : str=4 , a__ : int=1536 , a__ : Optional[Any]=1536 , a__ : str=0.0 , a__ : Optional[int]=0.0 , a__ : Optional[int]=50257 , a__ : int=True , a__ : Optional[int]=True , a__ : str="gelu" , a__ : List[str]=256 , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Any=0.0 , a__ : str=0.02 , a__ : str=False , a__ : int=1500 , a__ : Tuple=448 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Tuple=None , a__ : List[Any]=[220, 50256] , a__ : Optional[int]=False , a__ : Optional[Any]=256 , a__ : Any=False , a__ : int=0.05 , a__ : Optional[Any]=10 , a__ : Dict=2 , a__ : Optional[Any]=0.0 , a__ : Tuple=10 , a__ : Any=0 , a__ : str=7 , **a__ : Any , ): UpperCAmelCase = vocab_size UpperCAmelCase = num_mel_bins UpperCAmelCase = d_model UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size UpperCAmelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks UpperCAmelCase = median_filter_width super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , suppress_tokens=a__ , begin_suppress_tokens=a__ , **a__ , ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : List[str] ): UpperCAmelCase = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: UpperCAmelCase = {0: '''batch'''} else: UpperCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs def __snake_case ( self : str , a__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a__ : int = -1 , a__ : int = -1 , a__ : bool = False , a__ : Optional["TensorType"] = None , a__ : int = 22050 , a__ : float = 5.0 , a__ : int = 220 , ): UpperCAmelCase = OrderedDict() UpperCAmelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a__ , framework=a__ , sampling_rate=a__ , time_duration=a__ , frequency=a__ , ) UpperCAmelCase = encoder_inputs['''input_features'''].shape[2] UpperCAmelCase = encoder_sequence_length // 2 if self.use_past else seq_length UpperCAmelCase = super().generate_dummy_inputs( preprocessor.tokenizer , a__ , a__ , a__ , a__ ) UpperCAmelCase = encoder_inputs.pop('''input_features''' ) UpperCAmelCase = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: UpperCAmelCase = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __snake_case ( self : Dict ): return 1e-3
51
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a = logging.get_logger(__name__) a = { '''google/vit-base-patch16-224''': '''https://huggingface.co/vit-base-patch16-224/resolve/main/config.json''', # See all ViT models at https://huggingface.co/models?filter=vit } class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : str = '''vit''' def __init__( self : Dict , _UpperCAmelCase : Dict=768 , _UpperCAmelCase : List[str]=12 , _UpperCAmelCase : Tuple=12 , _UpperCAmelCase : Optional[Any]=3_072 , _UpperCAmelCase : List[Any]="gelu" , _UpperCAmelCase : List[str]=0.0 , _UpperCAmelCase : str=0.0 , _UpperCAmelCase : Any=0.02 , _UpperCAmelCase : List[Any]=1E-1_2 , _UpperCAmelCase : Union[str, Any]=224 , _UpperCAmelCase : Union[str, Any]=16 , _UpperCAmelCase : List[Any]=3 , _UpperCAmelCase : str=True , _UpperCAmelCase : Tuple=16 , **_UpperCAmelCase : List[Any] , ): super().__init__(**_UpperCAmelCase ) _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = initializer_range _A = layer_norm_eps _A = image_size _A = patch_size _A = num_channels _A = qkv_bias _A = encoder_stride class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : Dict = version.parse('''1.11''' ) @property def lowerCAmelCase_ ( self : int ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def lowerCAmelCase_ ( self : int ): return 1E-4
7
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =LEDConfig _lowerCamelCase ={} _lowerCamelCase ="gelu" def __init__( self : Tuple , a__ : Any , a__ : int=13 , a__ : List[Any]=7 , a__ : int=True , a__ : Union[str, Any]=False , a__ : Tuple=99 , a__ : Any=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : List[Any]=37 , a__ : List[Any]=0.1 , a__ : Any=0.1 , a__ : Optional[int]=20 , a__ : List[Any]=2 , a__ : Union[str, Any]=1 , a__ : List[Any]=0 , a__ : Union[str, Any]=4 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after UpperCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests UpperCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) UpperCAmelCase = prepare_led_inputs_dict(a__ , a__ , a__ ) UpperCAmelCase = tf.concat( [tf.zeros_like(a__ )[:, :-1], tf.ones_like(a__ )[:, -1:]] , axis=-1 , ) UpperCAmelCase = global_attention_mask return config, inputs_dict def __snake_case ( self : Optional[int] , a__ : List[str] , a__ : int ): UpperCAmelCase = TFLEDModel(config=a__ ).get_decoder() UpperCAmelCase = inputs_dict['''input_ids'''] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(a__ , attention_mask=a__ , use_cache=a__ ) UpperCAmelCase, UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(a__ , attention_mask=a__ )[0] UpperCAmelCase = model(a__ , attention_mask=a__ , past_key_values=a__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(a__ , a__ , rtol=1e-3 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=None , ) -> Dict: """simple docstring""" if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowerCamelCase =(TFLEDForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase =( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : Optional[Any] ): UpperCAmelCase = TFLEDModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ ) def __snake_case ( self : int ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = tf.zeros_like(inputs_dict['''attention_mask'''] ) UpperCAmelCase = 2 UpperCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) UpperCAmelCase = True UpperCAmelCase = self.model_tester.seq_length UpperCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(a__ : Tuple ): UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(a__ : int ): UpperCAmelCase = [t.numpy() for t in outputs.encoder_attentions] UpperCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = len(a__ ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) if self.is_encoder_decoder: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_decoder_attentions_output(a__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) ) self.assertEqual(model.config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __snake_case ( self : Any ): pass def __snake_case ( self : Union[str, Any] ): # TODO: Head-masking not yet implement pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> Tuple: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE_ , dtype=tf.intaa ) a__ : int = 1e-4 @slow @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, 768) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 ) def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 , rtol=1e-3 )
51
0
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE (a__ ): lowerCAmelCase = ['''image_processor''', '''tokenizer'''] lowerCAmelCase = '''AutoImageProcessor''' lowerCAmelCase = '''AutoTokenizer''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' super().__init__(_UpperCAmelCase , _UpperCAmelCase) __A : Optional[Any] = self.image_processor def __call__( self , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , **_UpperCAmelCase): '''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 : int = self.tokenizer(_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase) if images is not None: __A : List[Any] = self.image_processor(_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase) if text is not None and images is not None: __A : int = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_UpperCAmelCase) , tensor_type=_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , *_UpperCAmelCase , **_UpperCAmelCase): '''simple docstring''' return self.tokenizer.batch_decode(*_UpperCAmelCase , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , *_UpperCAmelCase , **_UpperCAmelCase): '''simple docstring''' return self.tokenizer.decode(*_UpperCAmelCase , **_UpperCAmelCase) @property def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
8
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : List[Any] = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTMAEForPreTraining''', '''ViTMAELayer''', '''ViTMAEModel''', '''ViTMAEPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''TFViTMAEForPreTraining''', '''TFViTMAEModel''', '''TFViTMAEPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
9
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "openai/imagegpt-small": "", "openai/imagegpt-medium": "", "openai/imagegpt-large": "", } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "imagegpt" UpperCAmelCase = ["past_key_values"] UpperCAmelCase = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : int , _A : Any=512 + 1 , _A : Tuple=32 * 32 , _A : Union[str, Any]=512 , _A : Union[str, Any]=24 , _A : Dict=8 , _A : List[str]=None , _A : List[Any]="quick_gelu" , _A : int=0.1 , _A : Optional[Any]=0.1 , _A : int=0.1 , _A : int=1e-5 , _A : List[str]=0.02 , _A : Optional[Any]=True , _A : List[str]=True , _A : Any=False , _A : Optional[Any]=False , _A : List[str]=False , **_A : Any , ): _UpperCamelCase = vocab_size _UpperCamelCase = n_positions _UpperCamelCase = n_embd _UpperCamelCase = n_layer _UpperCamelCase = n_head _UpperCamelCase = n_inner _UpperCamelCase = activation_function _UpperCamelCase = resid_pdrop _UpperCamelCase = embd_pdrop _UpperCamelCase = attn_pdrop _UpperCamelCase = layer_norm_epsilon _UpperCamelCase = initializer_range _UpperCamelCase = scale_attn_weights _UpperCamelCase = use_cache _UpperCamelCase = scale_attn_by_inverse_layer_idx _UpperCamelCase = reorder_and_upcast_attn _UpperCamelCase = tie_word_embeddings super().__init__(tie_word_embeddings=_A , **_A ) class lowerCAmelCase_ ( __lowercase ): @property def UpperCamelCase_ ( self : List[str] ): return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ] ) def UpperCamelCase_ ( self : Any , _A : "FeatureExtractionMixin" , _A : int = 1 , _A : int = -1 , _A : bool = False , _A : Optional["TensorType"] = None , _A : int = 3 , _A : int = 32 , _A : int = 32 , ): _UpperCamelCase = self._generate_dummy_images(_A , _A , _A , _A ) _UpperCamelCase = dict(preprocessor(images=_A , return_tensors=_A ) ) return inputs
10
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : Union[str, Any] , a__ : List[str]=None , a__ : Union[str, Any]=None , **a__ : Optional[Any] ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Any , a__ : Any=None , a__ : str=None , a__ : List[Any]=None , **a__ : List[str] ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : Optional[Any] , *a__ : int , **a__ : List[Any] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : Any , *a__ : Union[str, Any] , **a__ : Any ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
51
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = {"configuration_deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig", "DeiTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["DeiTFeatureExtractor"] lowercase_ = ["DeiTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "DeiTForImageClassification", "DeiTForImageClassificationWithTeacher", "DeiTForMaskedImageModeling", "DeiTModel", "DeiTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher", "TFDeiTForMaskedImageModeling", "TFDeiTModel", "TFDeiTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
11
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
0
def UpperCamelCase ( lowercase_ ) -> bool: '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def UpperCamelCase ( lowercase_ ) -> bool: '''simple docstring''' lowercase__ : int = credit_card_number lowercase__ : Dict = 0 lowercase__ : Dict = len(lowercase_ ) - 2 for i in range(lowercase_ , -1 , -2 ): # double the value of every second digit lowercase__ : str = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 lowercase__ : Optional[int] = cc_number[:i] + str(lowercase_ ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(lowercase_ ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def UpperCamelCase ( lowercase_ ) -> bool: '''simple docstring''' lowercase__ : str = F'{credit_card_number} is an invalid credit card number because' if not credit_card_number.isdigit(): print(F'{error_message} it has nonnumerical characters.' ) return False if not 13 <= len(lowercase_ ) <= 16: print(F'{error_message} of its length.' ) return False if not validate_initial_digits(lowercase_ ): print(F'{error_message} of its first two digits.' ) return False if not luhn_validation(lowercase_ ): print(F'{error_message} it fails the Luhn check.' ) return False print(F'{credit_card_number} is a valid credit card number.' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("""4111111111111111""") validate_credit_card_number("""32323""")
12
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ): pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _lowerCamelCase =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ): UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __snake_case ( self : int , a__ : Dict , a__ : Tuple ): pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __snake_case ( self : str ): pass @slow @require_torch def __snake_case ( self : Optional[Any] ): UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __snake_case ( self : Dict ): UpperCAmelCase = '''facebook/sam-vit-huge''' UpperCAmelCase = pipeline('''mask-generation''' , model=a__ ) UpperCAmelCase = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, ] , )
51
0
'''simple docstring''' import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() A__ : Union[str, Any] = logging.get_logger(__name__) A__ : Union[str, Any] = {name: getattr(transformers, name + """Fast""") for name in SLOW_TO_FAST_CONVERTERS} def UpperCAmelCase__ ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any ) -> Union[str, Any]: if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : List[str] = TOKENIZER_CLASSES else: __lowerCamelCase : List[Any] = {tokenizer_name: getattr(UpperCAmelCase_ , tokenizer_name + 'Fast' )} logger.info(F'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : Dict = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[Any] = True if checkpoint_name is None: __lowerCamelCase : Dict = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : int = [checkpoint_name] logger.info(F'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(F'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Any = tokenizer_class.from_pretrained(UpperCAmelCase_ , force_download=UpperCAmelCase_ ) # Save fast tokenizer logger.info(F'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Dict = checkpoint.split('/' ) __lowerCamelCase : List[Any] = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) elif add_prefix: __lowerCamelCase : int = checkpoint __lowerCamelCase : Tuple = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : str = dump_path logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : Any = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : List[Any] = file_path.split(UpperCAmelCase_ )[-1][0] if next_char == "/": __lowerCamelCase : Tuple = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) __lowerCamelCase : str = None logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Union[str, Any] = tokenizer.save_pretrained( UpperCAmelCase_ , legacy_format=UpperCAmelCase_ , filename_prefix=UpperCAmelCase_ ) logger.info(F'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(UpperCAmelCase_ ) logger.info(F'=> removing {file_name}' ) if __name__ == "__main__": A__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output generated fast tokenizer files.""" ) parser.add_argument( """--tokenizer_name""", default=None, type=str, help=( f'''Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ''' """download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--checkpoint_name""", default=None, type=str, help="""Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.""", ) parser.add_argument( """--force_download""", action="""store_true""", help="""Re-download checkpoints.""", ) A__ : List[str] = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
13
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
0
def __UpperCAmelCase ( __a : int ) -> str: """simple docstring""" _a : List[str] = int(__a ) if decimal in (0, 1): # Exit cases for the recursion return str(__a ) _a , _a : List[Any] = divmod(__a ,2 ) return binary_recursive(__a ) + str(__a ) def __UpperCAmelCase ( __a : str ) -> str: """simple docstring""" _a : Union[str, Any] = str(__a ).strip() if not number: raise ValueError('''No input value was provided''' ) _a : List[Any] = '''-''' if number.startswith('''-''' ) else '''''' _a : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F"""{negative}0b{binary_recursive(int(__a ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
14
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , a__ : List[str]="sayef/fsner-bert-base-uncased" ): super(a__ , self ).__init__() UpperCAmelCase = AutoModel.from_pretrained(a__ , return_dict=a__ ) UpperCAmelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCAmelCase = torch.nn.Softmax(dim=1 ) def __snake_case ( self : List[Any] , **a__ : Tuple ): return self.bert(**a__ ).last_hidden_state def __snake_case ( self : int , a__ : List[str] ): return token_embeddings.sum(2 , keepdim=a__ ) def __snake_case ( self : str , a__ : str , a__ : str , a__ : int=1 ): return self.softmax(T * self.cos(a__ , a__ ) ) def __snake_case ( self : Tuple , a__ : Tuple , a__ : str ): UpperCAmelCase = W_supports['''sizes'''].tolist() UpperCAmelCase = W_supports['''start_token_id'''].item() UpperCAmelCase = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = W_supports['''input_ids'''] == start_token_id UpperCAmelCase = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(a__ ): if i == 0: UpperCAmelCase = 0 else: UpperCAmelCase = support_sizes[i - 1] UpperCAmelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase = torch.vstack((p_starts, p_start) ) UpperCAmelCase = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase = p_start UpperCAmelCase = p_end return p_starts, p_ends
51
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer A : Optional[Any] = logging.get_logger(__name__) A : str = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} A : Any = { 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } A : Dict = { 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } A : Optional[int] = { 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } A : int = { 'facebook/dpr-ctx_encoder-single-nq-base': 5_1_2, 'facebook/dpr-ctx_encoder-multiset-base': 5_1_2, } A : Optional[Any] = { 'facebook/dpr-question_encoder-single-nq-base': 5_1_2, 'facebook/dpr-question_encoder-multiset-base': 5_1_2, } A : Any = { 'facebook/dpr-reader-single-nq-base': 5_1_2, 'facebook/dpr-reader-multiset-base': 5_1_2, } A : Union[str, Any] = { 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } A : Tuple = { 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } A : Any = { 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = VOCAB_FILES_NAMES A__ = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ = DPRContextEncoderTokenizer class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = VOCAB_FILES_NAMES A__ = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ = DPRQuestionEncoderTokenizer A : Any = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) A : Optional[Any] = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) A : int = r'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(UpperCAmelCase__ ) class A : '''simple docstring''' def __call__(self : str , _UpperCAmelCase : str , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Optional[str] = None , _UpperCAmelCase : Union[bool, str] = False , _UpperCAmelCase : Union[bool, str] = False , _UpperCAmelCase : Optional[int] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : Optional[bool] = None , **_UpperCAmelCase : Any , ) -> BatchEncoding: """simple docstring""" if titles is None and texts is None: return super().__call__( _UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , **_UpperCAmelCase , ) elif titles is None or texts is None: lowercase__ = titles if texts is None else texts return super().__call__( _UpperCAmelCase , _UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , **_UpperCAmelCase , ) lowercase__ = titles if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) else [titles] lowercase__ = texts if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) else [texts] lowercase__ = len(_UpperCAmelCase ) lowercase__ = questions if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) else [questions] * n_passages assert len(_UpperCAmelCase ) == len( _UpperCAmelCase ), f'''There should be as many titles than texts but got {len(_UpperCAmelCase )} titles and {len(_UpperCAmelCase )} texts.''' lowercase__ = super().__call__(_UpperCAmelCase , _UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase )["""input_ids"""] lowercase__ = super().__call__(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase )["""input_ids"""] lowercase__ = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_UpperCAmelCase , _UpperCAmelCase ) ] } if return_attention_mask is not False: lowercase__ = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) lowercase__ = attention_mask return self.pad(_UpperCAmelCase , padding=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors=_UpperCAmelCase ) def lowerCamelCase__ (self : List[str] , _UpperCAmelCase : BatchEncoding , _UpperCAmelCase : DPRReaderOutput , _UpperCAmelCase : int = 16 , _UpperCAmelCase : int = 64 , _UpperCAmelCase : int = 4 , ) -> List[DPRSpanPrediction]: """simple docstring""" lowercase__ = reader_input["""input_ids"""] lowercase__ , lowercase__ , lowercase__ = reader_output[:3] lowercase__ = len(_UpperCAmelCase ) lowercase__ = sorted(range(_UpperCAmelCase ) , reverse=_UpperCAmelCase , key=relevance_logits.__getitem__ ) lowercase__ = [] for doc_id in sorted_docs: lowercase__ = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence lowercase__ = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: lowercase__ = sequence_ids.index(self.pad_token_id ) else: lowercase__ = len(_UpperCAmelCase ) lowercase__ = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_UpperCAmelCase , top_spans=_UpperCAmelCase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_UpperCAmelCase , start_index=_UpperCAmelCase , end_index=_UpperCAmelCase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_UpperCAmelCase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCamelCase__ (self : Optional[int] , _UpperCAmelCase : List[int] , _UpperCAmelCase : List[int] , _UpperCAmelCase : int , _UpperCAmelCase : int , ) -> List[DPRSpanPrediction]: """simple docstring""" lowercase__ = [] for start_index, start_score in enumerate(_UpperCAmelCase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) lowercase__ = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase : x[1] , reverse=_UpperCAmelCase ) lowercase__ = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f'''Wrong span indices: [{start_index}:{end_index}]''' lowercase__ = end_index - start_index + 1 assert length <= max_answer_length, f'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_UpperCAmelCase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase__ ) class A ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' A__ = VOCAB_FILES_NAMES A__ = READER_PRETRAINED_VOCAB_FILES_MAP A__ = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = READER_PRETRAINED_INIT_CONFIGURATION A__ = ['''input_ids''', '''attention_mask'''] A__ = DPRReaderTokenizer
15
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
0
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = KandinskyVaaControlnetPipeline lowerCamelCase__ = ["image_embeds", "negative_image_embeds", "hint"] lowerCamelCase__ = ["image_embeds", "negative_image_embeds", "hint"] lowerCamelCase__ = [ "generator", "height", "width", "latents", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCamelCase__ = False @property def _snake_case ( self : Union[str, Any] ): return 32 @property def _snake_case ( self : Optional[Any] ): return 32 @property def _snake_case ( self : Optional[Any] ): return self.time_input_dim @property def _snake_case ( self : Tuple ): return self.time_input_dim * 4 @property def _snake_case ( self : str ): return 100 @property def _snake_case ( self : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = { "in_channels": 8, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image_hint", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE = UNetaDConditionModel(**__lowerCamelCase ) return model @property def _snake_case ( self : Dict ): return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _snake_case ( self : Union[str, Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = VQModel(**self.dummy_movq_kwargs ) return model def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.dummy_unet SCREAMING_SNAKE_CASE = self.dummy_movq SCREAMING_SNAKE_CASE = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=__lowerCamelCase , set_alpha_to_one=__lowerCamelCase , steps_offset=1 , prediction_type="epsilon" , thresholding=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _snake_case ( self : int , __lowerCamelCase : Any , __lowerCamelCase : Any=0 ): SCREAMING_SNAKE_CASE = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowerCamelCase ) # create hint SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith("mps" ): SCREAMING_SNAKE_CASE = torch.manual_seed(__lowerCamelCase ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "hint": hint, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = "cpu" SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = pipe( **self.get_dummy_inputs(__lowerCamelCase ) , return_dict=__lowerCamelCase , )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy" ) SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/hint_image_cat.png" ) SCREAMING_SNAKE_CASE = torch.from_numpy(np.array(__lowerCamelCase ) ).float() / 255.0 SCREAMING_SNAKE_CASE = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = KandinskyVaaControlnetPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-controlnet-depth" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE = pipeline.to(__lowerCamelCase ) pipeline.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE = "A robot, 4k photo" SCREAMING_SNAKE_CASE = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pipe_prior( __lowerCamelCase , generator=__lowerCamelCase , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipeline( image_embeds=__lowerCamelCase , negative_image_embeds=__lowerCamelCase , hint=__lowerCamelCase , generator=__lowerCamelCase , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
16
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Dict = '''▁''' UpperCAmelCase_ : List[str] = { '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } UpperCAmelCase_ : Dict = { '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } UpperCAmelCase_ : Optional[Any] = { '''facebook/m2m100_418M''': 1_024, } # fmt: off UpperCAmelCase_ : List[Any] = { '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class lowerCamelCase_ ( _lowercase ): _lowercase : Optional[Any] = VOCAB_FILES_NAMES _lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : str = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = ['''input_ids''', '''attention_mask'''] _lowercase : List[int] = [] _lowercase : List[int] = [] def __init__( self : Dict , __A : Optional[Any] , __A : Any , __A : Tuple=None , __A : List[str]=None , __A : int="<s>" , __A : Union[str, Any]="</s>" , __A : Optional[Any]="</s>" , __A : Tuple="<pad>" , __A : List[str]="<unk>" , __A : Optional[Any]="m2m100" , __A : Optional[Dict[str, Any]] = None , __A : Any=8 , **__A : List[str] , ): __A : int = {} if sp_model_kwargs is None else sp_model_kwargs __A : List[Any] = language_codes __A : List[str] = FAIRSEQ_LANGUAGE_CODES[language_codes] __A : str = {lang_code: F"""__{lang_code}__""" for lang_code in fairseq_language_code} __A : Optional[int] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__A ) for lang_code in fairseq_language_code if self.get_lang_token(__A ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__A , tgt_lang=__A , bos_token=__A , eos_token=__A , sep_token=__A , unk_token=__A , pad_token=__A , language_codes=__A , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__A , **__A , ) __A : Any = vocab_file __A : Any = load_json(__A ) __A : Union[str, Any] = {v: k for k, v in self.encoder.items()} __A : Optional[int] = spm_file __A : Dict = load_spm(__A , self.sp_model_kwargs ) __A : int = len(self.encoder ) __A : Optional[Any] = { self.get_lang_token(__A ): self.encoder_size + i for i, lang_code in enumerate(__A ) } __A : Any = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__A )} __A : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} __A : Tuple = src_lang if src_lang is not None else """en""" __A : Dict = tgt_lang __A : List[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) __A : str = num_madeup_words @property def lowerCAmelCase_ ( self : Any ): return len(self.encoder ) + len(self.lang_token_to_id ) @property def lowerCAmelCase_ ( self : int ): return self._src_lang @src_lang.setter def lowerCAmelCase_ ( self : int , __A : str ): __A : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowerCAmelCase_ ( self : str , __A : str ): return self.sp_model.encode(__A , out_type=__A ) def lowerCAmelCase_ ( self : str , __A : Union[str, Any] ): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__A , self.encoder[self.unk_token] ) def lowerCAmelCase_ ( self : int , __A : int ): if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__A , self.unk_token ) def lowerCAmelCase_ ( self : Tuple , __A : Optional[Any] ): __A : Dict = [] __A : Tuple = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__A ) + token __A : Dict = [] else: current_sub_tokens.append(__A ) out_string += self.sp_model.decode(__A ) return out_string.strip() def lowerCAmelCase_ ( self : List[str] , __A : List[int] , __A : Optional[List[int]] = None , __A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) __A : Optional[Any] = [1] * len(self.prefix_tokens ) __A : Optional[Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def lowerCAmelCase_ ( self : Optional[int] , __A : List[int] , __A : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowerCAmelCase_ ( self : List[str] ): __A : Tuple = {self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): __A : List[str] = self.__dict__.copy() __A : Union[str, Any] = None return state def __setstate__( self : Dict , __A : Dict ): __A : List[str] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __A : Union[str, Any] = {} __A : str = load_spm(self.spm_file , self.sp_model_kwargs ) def lowerCAmelCase_ ( self : str , __A : str , __A : Optional[str] = None ): __A : str = Path(__A ) if not save_dir.is_dir(): raise OSError(F"""{save_directory} should be a directory""" ) __A : str = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) __A : Dict = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , __A ) if os.path.abspath(self.spm_file ) != os.path.abspath(__A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __A ) elif not os.path.isfile(self.spm_file ): with open(__A , """wb""" ) as fi: __A : str = self.sp_model.serialized_model_proto() fi.write(__A ) return (str(__A ), str(__A )) def lowerCAmelCase_ ( self : Union[str, Any] , __A : List[str] , __A : str = "en" , __A : Optional[List[str]] = None , __A : str = "ro" , **__A : Optional[int] , ): __A : Any = src_lang __A : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__A , __A , **__A ) def lowerCAmelCase_ ( self : int , __A : Dict , __A : Optional[str] , __A : Optional[str] , **__A : List[str] ): if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) __A : List[Any] = src_lang __A : str = self(__A , add_special_tokens=__A , **__A ) __A : Optional[int] = self.get_lang_id(__A ) __A : Optional[Any] = tgt_lang_id return inputs def lowerCAmelCase_ ( self : List[str] ): self.set_src_lang_special_tokens(self.src_lang ) def lowerCAmelCase_ ( self : Optional[Any] ): self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowerCAmelCase_ ( self : Dict , __A : str ): __A : Any = self.get_lang_token(__A ) __A : Any = self.lang_token_to_id[lang_token] __A : Any = [self.cur_lang_id] __A : Optional[Any] = [self.eos_token_id] def lowerCAmelCase_ ( self : int , __A : str ): __A : Tuple = self.get_lang_token(__A ) __A : Dict = self.lang_token_to_id[lang_token] __A : Union[str, Any] = [self.cur_lang_id] __A : str = [self.eos_token_id] def lowerCAmelCase_ ( self : Tuple , __A : str ): return self.lang_code_to_token[lang] def lowerCAmelCase_ ( self : str , __A : str ): __A : List[Any] = self.get_lang_token(__A ) return self.lang_token_to_id[lang_token] def __SCREAMING_SNAKE_CASE ( a__ : str ,a__ : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: __A : Optional[int] = sentencepiece.SentencePieceProcessor(**a__ ) spm.Load(str(a__ ) ) return spm def __SCREAMING_SNAKE_CASE ( a__ : str ) -> Union[Dict, List]: with open(a__ ,"""r""" ) as f: return json.load(a__ ) def __SCREAMING_SNAKE_CASE ( a__ : Optional[Any] ,a__ : str ) -> None: with open(a__ ,"""w""" ) as f: json.dump(a__ ,a__ ,indent=2 )
17
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" print('''Loading config file...''' ) def flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" , SCREAMING_SNAKE_CASE_ : Dict="." ): UpperCAmelCase = [] for k, v in d.items(): UpperCAmelCase = parent_key + sep + k if parent_key else k if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sep=SCREAMING_SNAKE_CASE_ ).items() ) else: items.append((new_key, v) ) return dict(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = argparse.Namespace() with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as yaml_file: try: UpperCAmelCase = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=yaml.FullLoader ) UpperCAmelCase = flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ ) for k, v in flat_cfg.items(): setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) ) return config def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase = MobileViTVaConfig() UpperCAmelCase = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase = 151 UpperCAmelCase = 512 UpperCAmelCase = '''ade20k-id2label.json''' UpperCAmelCase = True elif task_name.startswith('''voc_''' ): UpperCAmelCase = 21 UpperCAmelCase = 512 UpperCAmelCase = '''pascal-voc-id2label.json''' UpperCAmelCase = True # orig_config UpperCAmelCase = load_orig_config_file(SCREAMING_SNAKE_CASE_ ) assert getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" UpperCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = val def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str=False ) -> int: """simple docstring""" if base_model: UpperCAmelCase = '''''' else: UpperCAmelCase = '''mobilevitv2.''' UpperCAmelCase = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase = k[8:] else: UpperCAmelCase = k if ".block." in k: UpperCAmelCase = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase = k_new.replace('''conv_1.''' , f"{model_prefix}conv_stem." ) for i in [1, 2]: if f"layer_{i}." in k: UpperCAmelCase = k_new.replace(f"layer_{i}." , f"{model_prefix}encoder.layer.{i-1}.layer." ) if ".exp_1x1." in k: UpperCAmelCase = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f"layer_{i}.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.0." , f"{model_prefix}encoder.layer.{i-1}.downsampling_layer." ) if f"layer_{i}.1.local_rep.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.0." , f"{model_prefix}encoder.layer.{i-1}.conv_kxk." ) if f"layer_{i}.1.local_rep.1." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.1." , f"{model_prefix}encoder.layer.{i-1}.conv_1x1." ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase = [0, 1] elif i == 4: UpperCAmelCase = [0, 1, 2, 3] elif i == 5: UpperCAmelCase = [0, 1, 2] for j in j_in: if f"layer_{i}.1.global_rep.{j}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j}." , f"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." ) if f"layer_{i}.1.global_rep.{j+1}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j+1}." , f"{model_prefix}encoder.layer.{i-1}.layernorm." ) if f"layer_{i}.1.conv_proj." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.conv_proj." , f"{model_prefix}encoder.layer.{i-1}.conv_projection." ) if "pre_norm_attn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> int: """simple docstring""" UpperCAmelCase = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(SCREAMING_SNAKE_CASE_ ) for k in keys_to_ignore: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> List[Any]: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = get_mobilevitva_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False else: UpperCAmelCase = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False # remove and rename some keys of load the original model UpperCAmelCase = checkpoint remove_unused_keys(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load modified state_dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase = outputs.logits UpperCAmelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {task_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 __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
51
0
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def __a(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any]=0.999 , SCREAMING_SNAKE_CASE_ : List[str]="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : List[Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : str ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) _lowerCAmelCase = [] for i in range(SCREAMING_SNAKE_CASE_ ): _lowerCAmelCase = i / num_diffusion_timesteps _lowerCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) / alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) return torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) class lowerCAmelCase_ ( __magic_name__ ,__magic_name__ ): __lowerCamelCase : Optional[Any] = [e.name for e in KarrasDiffusionSchedulers] __lowerCamelCase : Any = 2 @register_to_config def __init__( self , _lowerCAmelCase = 1000 , _lowerCAmelCase = 0.00085 , _lowerCAmelCase = 0.012 , _lowerCAmelCase = "linear" , _lowerCAmelCase = None , _lowerCAmelCase = "epsilon" , _lowerCAmelCase = False , _lowerCAmelCase = False , _lowerCAmelCase = 1.0 , _lowerCAmelCase = "linspace" , _lowerCAmelCase = 0 , ) -> Union[str, Any]: if trained_betas is not None: _lowerCAmelCase = torch.tensor(_lowerCAmelCase , dtype=torch.floataa ) elif beta_schedule == "linear": _lowerCAmelCase = torch.linspace(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _lowerCAmelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _lowerCAmelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _lowerCAmelCase = betas_for_alpha_bar(_lowerCAmelCase , alpha_transform_type="cosine" ) elif beta_schedule == "exp": _lowerCAmelCase = betas_for_alpha_bar(_lowerCAmelCase , alpha_transform_type="exp" ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) _lowerCAmelCase = 1.0 - self.betas _lowerCAmelCase = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) _lowerCAmelCase = use_karras_sigmas def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase=None ) -> List[str]: if schedule_timesteps is None: _lowerCAmelCase = self.timesteps _lowerCAmelCase = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _lowerCAmelCase = 1 if len(_lowerCAmelCase ) > 1 else 0 else: _lowerCAmelCase = timestep.cpu().item() if torch.is_tensor(_lowerCAmelCase ) else timestep _lowerCAmelCase = self._index_counter[timestep_int] return indices[pos].item() @property def _snake_case ( self ) -> Union[str, Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , ) -> torch.FloatTensor: _lowerCAmelCase = self.index_for_timestep(_lowerCAmelCase ) _lowerCAmelCase = self.sigmas[step_index] _lowerCAmelCase = sample / ((sigma**2 + 1) ** 0.5) return sample def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , ) -> Any: _lowerCAmelCase = num_inference_steps _lowerCAmelCase = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _lowerCAmelCase = np.linspace(0 , num_train_timesteps - 1 , _lowerCAmelCase , dtype=_lowerCAmelCase )[::-1].copy() elif self.config.timestep_spacing == "leading": _lowerCAmelCase = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowerCAmelCase = (np.arange(0 , _lowerCAmelCase ) * step_ratio).round()[::-1].copy().astype(_lowerCAmelCase ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _lowerCAmelCase = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowerCAmelCase = (np.arange(_lowerCAmelCase , 0 , -step_ratio )).round().copy().astype(_lowerCAmelCase ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) _lowerCAmelCase = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _lowerCAmelCase = np.log(_lowerCAmelCase ) _lowerCAmelCase = np.interp(_lowerCAmelCase , np.arange(0 , len(_lowerCAmelCase ) ) , _lowerCAmelCase ) if self.config.use_karras_sigmas: _lowerCAmelCase = self._convert_to_karras(in_sigmas=_lowerCAmelCase , num_inference_steps=self.num_inference_steps ) _lowerCAmelCase = np.array([self._sigma_to_t(_lowerCAmelCase , _lowerCAmelCase ) for sigma in sigmas] ) _lowerCAmelCase = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _lowerCAmelCase = torch.from_numpy(_lowerCAmelCase ).to(device=_lowerCAmelCase ) _lowerCAmelCase = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _lowerCAmelCase = torch.from_numpy(_lowerCAmelCase ) _lowerCAmelCase = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(_lowerCAmelCase ).startswith("mps" ): # mps does not support float64 _lowerCAmelCase = timesteps.to(_lowerCAmelCase , dtype=torch.floataa ) else: _lowerCAmelCase = timesteps.to(device=_lowerCAmelCase ) # empty dt and derivative _lowerCAmelCase = None _lowerCAmelCase = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _lowerCAmelCase = defaultdict(_lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: # get log sigma _lowerCAmelCase = np.log(_lowerCAmelCase ) # get distribution _lowerCAmelCase = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _lowerCAmelCase = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _lowerCAmelCase = low_idx + 1 _lowerCAmelCase = log_sigmas[low_idx] _lowerCAmelCase = log_sigmas[high_idx] # interpolate sigmas _lowerCAmelCase = (low - log_sigma) / (low - high) _lowerCAmelCase = np.clip(_lowerCAmelCase , 0 , 1 ) # transform interpolation to time range _lowerCAmelCase = (1 - w) * low_idx + w * high_idx _lowerCAmelCase = t.reshape(sigma.shape ) return t def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> torch.FloatTensor: _lowerCAmelCase = in_sigmas[-1].item() _lowerCAmelCase = in_sigmas[0].item() _lowerCAmelCase = 7.0 # 7.0 is the value used in the paper _lowerCAmelCase = np.linspace(0 , 1 , _lowerCAmelCase ) _lowerCAmelCase = sigma_min ** (1 / rho) _lowerCAmelCase = sigma_max ** (1 / rho) _lowerCAmelCase = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _snake_case ( self ) -> Tuple: return self.dt is None def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = True , ) -> Union[SchedulerOutput, Tuple]: _lowerCAmelCase = self.index_for_timestep(_lowerCAmelCase ) # advance index counter by 1 _lowerCAmelCase = timestep.cpu().item() if torch.is_tensor(_lowerCAmelCase ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _lowerCAmelCase = self.sigmas[step_index] _lowerCAmelCase = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _lowerCAmelCase = self.sigmas[step_index - 1] _lowerCAmelCase = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _lowerCAmelCase = 0 _lowerCAmelCase = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _lowerCAmelCase = sigma_hat if self.state_in_first_order else sigma_next _lowerCAmelCase = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _lowerCAmelCase = sigma_hat if self.state_in_first_order else sigma_next _lowerCAmelCase = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _lowerCAmelCase = model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.config.clip_sample: _lowerCAmelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _lowerCAmelCase = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _lowerCAmelCase = sigma_next - sigma_hat # store for 2nd order step _lowerCAmelCase = derivative _lowerCAmelCase = dt _lowerCAmelCase = sample else: # 2. 2nd order / Heun's method _lowerCAmelCase = (sample - pred_original_sample) / sigma_next _lowerCAmelCase = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _lowerCAmelCase = self.dt _lowerCAmelCase = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples _lowerCAmelCase = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_lowerCAmelCase ): # mps does not support float64 _lowerCAmelCase = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _lowerCAmelCase = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _lowerCAmelCase = self.timesteps.to(original_samples.device ) _lowerCAmelCase = timesteps.to(original_samples.device ) _lowerCAmelCase = [self.index_for_timestep(_lowerCAmelCase , _lowerCAmelCase ) for t in timesteps] _lowerCAmelCase = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _lowerCAmelCase = sigma.unsqueeze(-1 ) _lowerCAmelCase = original_samples + noise * sigma return noisy_samples def __len__( self ) -> List[str]: return self.config.num_train_timesteps
18
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="megatron-bert" def __init__( self : Dict , a__ : Union[str, Any]=29056 , a__ : Dict=1024 , a__ : str=24 , a__ : Any=16 , a__ : Tuple=4096 , a__ : Optional[int]="gelu" , a__ : Tuple=0.1 , a__ : Tuple=0.1 , a__ : Any=512 , a__ : Optional[Any]=2 , a__ : str=0.02 , a__ : Optional[int]=1e-1_2 , a__ : Union[str, Any]=0 , a__ : Optional[Any]="absolute" , a__ : Dict=True , **a__ : Dict , ): super().__init__(pad_token_id=a__ , **a__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache
51
0
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def lowerCamelCase__ ( ) -> Dict: """simple docstring""" _UpperCamelCase = HfArgumentParser(__snake_case ) _UpperCamelCase = parser.parse_args_into_dataclasses()[0] _UpperCamelCase = TensorFlowBenchmark(args=__snake_case ) try: _UpperCamelCase = parser.parse_args_into_dataclasses()[0] except ValueError as e: _UpperCamelCase = '''Arg --no_{0} is no longer used, please use --no-{0} instead.''' _UpperCamelCase = ''' '''.join(str(__snake_case ).split(''' ''' )[:-1] ) _UpperCamelCase = '''''' _UpperCamelCase = eval(str(__snake_case ).split(''' ''' )[-1] ) _UpperCamelCase = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _UpperCamelCase = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
19
'''simple docstring''' from __future__ import annotations a__ : List[str] = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , a__ : dict[str, list[str]] , a__ : str ): UpperCAmelCase = graph # mapping node to its parent in resulting breadth first tree UpperCAmelCase = {} UpperCAmelCase = source_vertex def __snake_case ( self : Optional[int] ): UpperCAmelCase = {self.source_vertex} UpperCAmelCase = None UpperCAmelCase = [self.source_vertex] # first in first out queue while queue: UpperCAmelCase = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(a__ ) UpperCAmelCase = vertex queue.append(a__ ) def __snake_case ( self : Any , a__ : str ): if target_vertex == self.source_vertex: return self.source_vertex UpperCAmelCase = self.parent.get(a__ ) if target_vertex_parent is None: UpperCAmelCase = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(a__ ) return self.shortest_path(a__ ) + f"->{target_vertex}" if __name__ == "__main__": a__ : Tuple = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
51
0
def _lowercase( __a : int , __a : int ): if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) a__ =str(bin(__a ) ) binary_number += "0" * shift_amount return binary_number def _lowercase( __a : int , __a : int ): if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) a__ =str(bin(__a ) )[2:] if shift_amount >= len(__a ): return "0b0" a__ =binary_number[: len(__a ) - shift_amount] return "0b" + shifted_binary_number def _lowercase( __a : int , __a : int ): if number >= 0: # Get binary representation of positive number a__ ='0' + str(bin(__a ) ).strip('-' )[2:] else: # Get binary (2's complement) representation of negative number a__ =len(bin(__a )[3:] ) # Find 2's complement of number a__ =bin(abs(__a ) - (1 << binary_number_length) )[3:] a__ =( '1' + '0' * (binary_number_length - len(__a )) + binary_number ) if shift_amount >= len(__a ): return "0b" + binary_number[0] * len(__a ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(__a ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
20
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : Tuple = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys a__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ : Optional[Any] = { "configuration_table_transformer": [ "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TableTransformerConfig", "TableTransformerOnnxConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[int] = [ "TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TableTransformerForObjectDetection", "TableTransformerModel", "TableTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys UpperCAmelCase_ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
21
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Any = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
0
'''simple docstring''' def snake_case_ (UpperCamelCase : list , UpperCamelCase : list ): '''simple docstring''' _validate_point(UpperCamelCase ) _validate_point(UpperCamelCase ) if len(UpperCamelCase ) != len(UpperCamelCase ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(a - b ) for a, b in zip(UpperCamelCase , UpperCamelCase ) ) ) def snake_case_ (UpperCamelCase : list[float] ): '''simple docstring''' if point: if isinstance(UpperCamelCase , UpperCamelCase ): for item in point: if not isinstance(UpperCamelCase , (int, float) ): _a = ( '''Expected a list of numbers as input, found ''' f'{type(UpperCamelCase ).__name__}' ) raise TypeError(UpperCamelCase ) else: _a = f'Expected a list of numbers as input, found {type(UpperCamelCase ).__name__}' raise TypeError(UpperCamelCase ) else: raise ValueError('''Missing an input''' ) def snake_case_ (UpperCamelCase : list , UpperCamelCase : list ): '''simple docstring''' _validate_point(UpperCamelCase ) _validate_point(UpperCamelCase ) if len(UpperCamelCase ) != len(UpperCamelCase ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(x - y ) for x, y in zip(UpperCamelCase , UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
22
'''simple docstring''' from math import factorial def __snake_case ( SCREAMING_SNAKE_CASE_ : int = 100 ) -> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
51
0
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def _snake_case (__lowercase , __lowercase): UpperCamelCase_ = f"""{sampling_rate}""" UpperCamelCase_ = '1' UpperCamelCase_ = 'f32le' UpperCamelCase_ = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(__lowercase , stdin=subprocess.PIPE , stdout=subprocess.PIPE) as ffmpeg_process: UpperCamelCase_ = ffmpeg_process.communicate(__lowercase) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename') from error UpperCamelCase_ = output_stream[0] UpperCamelCase_ = np.frombuffer(__lowercase , np.floataa) if audio.shape[0] == 0: raise ValueError('Malformed soundfile') return audio def _snake_case (__lowercase , __lowercase , __lowercase = "f32le" , ): UpperCamelCase_ = f"""{sampling_rate}""" UpperCamelCase_ = '1' if format_for_conversion == "s16le": UpperCamelCase_ = 2 elif format_for_conversion == "f32le": UpperCamelCase_ = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""") UpperCamelCase_ = platform.system() if system == "Linux": UpperCamelCase_ = 'alsa' UpperCamelCase_ = 'default' elif system == "Darwin": UpperCamelCase_ = 'avfoundation' UpperCamelCase_ = ':0' elif system == "Windows": UpperCamelCase_ = 'dshow' UpperCamelCase_ = 'default' UpperCamelCase_ = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] UpperCamelCase_ = int(round(sampling_rate * chunk_length_s)) * size_of_sample UpperCamelCase_ = _ffmpeg_stream(__lowercase , __lowercase) for item in iterator: yield item def _snake_case (__lowercase , __lowercase , __lowercase = None , __lowercase = None , __lowercase = "f32le" , ): if stream_chunk_s is not None: UpperCamelCase_ = stream_chunk_s else: UpperCamelCase_ = chunk_length_s UpperCamelCase_ = ffmpeg_microphone(__lowercase , __lowercase , format_for_conversion=__lowercase) if format_for_conversion == "s16le": UpperCamelCase_ = np.intaa UpperCamelCase_ = 2 elif format_for_conversion == "f32le": UpperCamelCase_ = np.floataa UpperCamelCase_ = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""") if stride_length_s is None: UpperCamelCase_ = chunk_length_s / 6 UpperCamelCase_ = int(round(sampling_rate * chunk_length_s)) * size_of_sample if isinstance(__lowercase , (int, float)): UpperCamelCase_ = [stride_length_s, stride_length_s] UpperCamelCase_ = int(round(sampling_rate * stride_length_s[0])) * size_of_sample UpperCamelCase_ = int(round(sampling_rate * stride_length_s[1])) * size_of_sample UpperCamelCase_ = datetime.datetime.now() UpperCamelCase_ = datetime.timedelta(seconds=__lowercase) for item in chunk_bytes_iter(__lowercase , __lowercase , stride=(stride_left, stride_right) , stream=__lowercase): # Put everything back in numpy scale UpperCamelCase_ = np.frombuffer(item['raw'] , dtype=__lowercase) UpperCamelCase_ = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) UpperCamelCase_ = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def _snake_case (__lowercase , __lowercase , __lowercase , __lowercase = False): UpperCamelCase_ = B'' UpperCamelCase_ , UpperCamelCase_ = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""") UpperCamelCase_ = 0 for raw in iterator: acc += raw if stream and len(__lowercase) < chunk_len: UpperCamelCase_ = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(__lowercase) >= chunk_len: # We are flushing the accumulator UpperCamelCase_ = (_stride_left, stride_right) UpperCamelCase_ = {'raw': acc[:chunk_len], 'stride': stride} if stream: UpperCamelCase_ = False yield item UpperCamelCase_ = stride_left UpperCamelCase_ = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(__lowercase) > stride_left: UpperCamelCase_ = {'raw': acc, 'stride': (_stride_left, 0)} if stream: UpperCamelCase_ = False yield item def _snake_case (__lowercase , __lowercase): UpperCamelCase_ = 2**24 # 16Mo try: with subprocess.Popen(__lowercase , stdout=subprocess.PIPE , bufsize=__lowercase) as ffmpeg_process: while True: UpperCamelCase_ = ffmpeg_process.stdout.read(__lowercase) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename') from error
23
'''simple docstring''' import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =StableUnCLIPPipeline _lowerCamelCase =TEXT_TO_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase =TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _lowerCamelCase =False def __snake_case ( self : str ): UpperCAmelCase = 32 UpperCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=a__ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) UpperCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=a__ , num_layers=1 , ) torch.manual_seed(0 ) UpperCAmelCase = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1000 , clip_sample=a__ , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) UpperCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=a__ ) UpperCAmelCase = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a__ , projection_dim=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 , ) ) torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a__ , layers_per_block=1 , upcast_attention=a__ , use_linear_projection=a__ , ) torch.manual_seed(0 ) UpperCAmelCase = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=a__ , steps_offset=1 , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL() UpperCAmelCase = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def __snake_case ( self : str , a__ : Dict , a__ : List[str]=0 ): if str(a__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(a__ ) else: UpperCAmelCase = torch.Generator(device=a__ ).manual_seed(a__ ) UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __snake_case ( self : List[Any] ): UpperCAmelCase = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=a__ ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[int] ): UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = pipe('''anime turle''' , generator=a__ , output_type='''np''' ) UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ ) def __snake_case ( self : str ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
51
0
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCAmelCase ( nn.Module): def __init__( self , __SCREAMING_SNAKE_CASE = 16 , __SCREAMING_SNAKE_CASE = 88 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = 1 , __SCREAMING_SNAKE_CASE = 0.0 , __SCREAMING_SNAKE_CASE = 32 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "geglu" , __SCREAMING_SNAKE_CASE = None , ) -> Optional[int]: '''simple docstring''' super().__init__() __snake_case = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , in_channels=__SCREAMING_SNAKE_CASE , num_layers=__SCREAMING_SNAKE_CASE , dropout=__SCREAMING_SNAKE_CASE , norm_num_groups=__SCREAMING_SNAKE_CASE , cross_attention_dim=__SCREAMING_SNAKE_CASE , attention_bias=__SCREAMING_SNAKE_CASE , sample_size=__SCREAMING_SNAKE_CASE , num_vector_embeds=__SCREAMING_SNAKE_CASE , activation_fn=__SCREAMING_SNAKE_CASE , num_embeds_ada_norm=__SCREAMING_SNAKE_CASE , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference __snake_case = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` __snake_case = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` __snake_case = [1, 0] def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = True , ) -> List[str]: '''simple docstring''' __snake_case = hidden_states __snake_case = [] __snake_case = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens __snake_case = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] __snake_case = self.transformer_index_for_condition[i] __snake_case = self.transformers[transformer_index]( __SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , timestep=__SCREAMING_SNAKE_CASE , cross_attention_kwargs=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] __snake_case = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) __snake_case = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__SCREAMING_SNAKE_CASE )
24
'''simple docstring''' def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Dict: """simple docstring""" if not head: return True # split the list to two parts UpperCAmelCase, UpperCAmelCase = head.next, head while fast and fast.next: UpperCAmelCase = fast.next.next UpperCAmelCase = slow.next UpperCAmelCase = slow.next UpperCAmelCase = None # Don't forget here! But forget still works! # reverse the second part UpperCAmelCase = None while second: UpperCAmelCase = second.next UpperCAmelCase = node UpperCAmelCase = second UpperCAmelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False UpperCAmelCase = node.next UpperCAmelCase = head.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> Union[str, Any]: """simple docstring""" if not head or not head.next: return True # 1. Get the midpoint (slow) UpperCAmelCase = UpperCAmelCase = UpperCAmelCase = head while fast and fast.next: UpperCAmelCase, UpperCAmelCase = fast.next.next, slow.next # 2. Push the second half into the stack UpperCAmelCase = [slow.val] while slow.next: UpperCAmelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False UpperCAmelCase = cur.next return True def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Tuple: """simple docstring""" if not head or not head.next: return True UpperCAmelCase = {} UpperCAmelCase = 0 while head: if head.val in d: d[head.val].append(SCREAMING_SNAKE_CASE_ ) else: UpperCAmelCase = [pos] UpperCAmelCase = head.next pos += 1 UpperCAmelCase = pos - 1 UpperCAmelCase = 0 for v in d.values(): if len(SCREAMING_SNAKE_CASE_ ) % 2 != 0: middle += 1 else: UpperCAmelCase = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): if v[i] + v[len(SCREAMING_SNAKE_CASE_ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
51
0
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ = 'true' def lowerCamelCase__ ( _a , _a=82 , _a=16): set_seed(42) SCREAMING_SNAKE_CASE : List[Any] = RegressionModel() SCREAMING_SNAKE_CASE : Optional[Any] = deepcopy(_a) SCREAMING_SNAKE_CASE : Any = RegressionDataset(length=_a) SCREAMING_SNAKE_CASE : List[Any] = DataLoader(_a , batch_size=_a) model.to(accelerator.device) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = accelerator.prepare(_a , _a) return model, ddp_model, dataloader def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased") SCREAMING_SNAKE_CASE : Optional[int] = load_dataset("glue" , "mrpc" , split="validation") def tokenize_function(_a): SCREAMING_SNAKE_CASE : str = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_a , max_length=_a) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE : Union[str, Any] = dataset.map( _a , batched=_a , remove_columns=["idx", "sentence1", "sentence2"] , ) SCREAMING_SNAKE_CASE : Any = tokenized_datasets.rename_column("label" , "labels") def collate_fn(_a): if use_longest: return tokenizer.pad(_a , padding="longest" , return_tensors="pt") return tokenizer.pad(_a , padding="max_length" , max_length=128 , return_tensors="pt") return DataLoader(_a , shuffle=_a , collate_fn=_a , batch_size=16) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Any = Accelerator(dispatch_batches=_a , split_batches=_a) SCREAMING_SNAKE_CASE : str = get_dataloader(_a , not dispatch_batches) SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained( "hf-internal-testing/mrpc-bert-base-cased" , return_dict=_a) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = accelerator.prepare(_a , _a) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = [] for batch in dataloader: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(_a) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = [], [] for logit, targ in logits_and_targets: logits.append(_a) targs.append(_a) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = torch.cat(_a), torch.cat(_a) return logits, targs def lowerCamelCase__ ( _a , _a=82 , _a=False , _a=False , _a=16): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = get_basic_setup(_a , _a , _a) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = generate_predictions(_a , _a , _a) assert ( len(_a) == num_samples ), f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_a)}" def lowerCamelCase__ ( _a = False , _a = False): SCREAMING_SNAKE_CASE : List[str] = evaluate.load("glue" , "mrpc") SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = get_mrpc_setup(_a , _a) # First do baseline SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = setup["no"] model.to(_a) model.eval() for batch in dataloader: batch.to(_a) with torch.inference_mode(): SCREAMING_SNAKE_CASE : Union[str, Any] = model(**_a) SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_a , references=batch["labels"]) SCREAMING_SNAKE_CASE : Dict = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = setup["ddp"] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE : Optional[int] = model(**_a) SCREAMING_SNAKE_CASE : Tuple = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE : Union[str, Any] = batch["labels"] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_a , references=_a) SCREAMING_SNAKE_CASE : Dict = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), f"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n" def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = Accelerator(split_batches=_a , dispatch_batches=_a) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("**Testing gather_for_metrics**") for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`") test_mrpc(_a , _a) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test torch metrics**") for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE : Tuple = Accelerator(split_batches=_a , dispatch_batches=_a) if accelerator.is_local_main_process: print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99") test_torch_metrics(_a , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test last batch is not dropped when perfectly divisible**") SCREAMING_SNAKE_CASE : str = Accelerator() test_torch_metrics(_a , 512) accelerator.state._reset_state() def lowerCamelCase__ ( _a): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
25
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Tuple , a__ : List[Any]=None , a__ : str=None , **a__ : Tuple ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Optional[Any] , a__ : Optional[int]=None , a__ : List[str]=None , a__ : int=None , **a__ : Tuple ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : List[str] , *a__ : Union[str, Any] , **a__ : Optional[int] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : int , *a__ : Optional[int] , **a__ : int ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : str ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __snake_case ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a__ , ) return self.image_processor_class @property def __snake_case ( self : List[Any] ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a__ , ) return self.image_processor
51
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys __UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =XGLMTokenizer _lowerCamelCase =XGLMTokenizerFast _lowerCamelCase =True _lowerCamelCase =True def __snake_case ( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[Any] ): UpperCAmelCase = '''<pad>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(a__ ) , 1008 ) def __snake_case ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[Any] ): UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(a__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( a__ , [ 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''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ 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 __snake_case ( self : Optional[Any] ): return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def __snake_case ( self : Optional[int] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=a__ ) UpperCAmelCase = pickle.dumps(a__ ) pickle.loads(a__ ) def __snake_case ( self : Tuple ): if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = '''I was born in 92000, and this is falsé.''' UpperCAmelCase = tokenizer.tokenize(a__ ) UpperCAmelCase = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = tokenizer.encode(a__ , add_special_tokens=a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(a__ ) UpperCAmelCase = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __snake_case ( self : int ): UpperCAmelCase = '''Hello World!''' UpperCAmelCase = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : List[str] ): UpperCAmelCase = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth''' ) # fmt: off UpperCAmelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __snake_case ( self : Any ): # fmt: off UpperCAmelCase = { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name='''facebook/xglm-564M''' , padding=a__ , )
51
0
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels __A : Optional[Any] = object() # For specifying empty leaf dict `{}` __A : Union[str, Any] = object() def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _A = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - len(_SCREAMING_SNAKE_CASE ) + 1 ): _A = [x.match(_SCREAMING_SNAKE_CASE ) for x, y in zip(_SCREAMING_SNAKE_CASE , ks[i:] )] if matches and all(_SCREAMING_SNAKE_CASE ): return True return False def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" def replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for rule, replacement in rules: if _match(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return replacement return val return replace def __lowerCAmelCase( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , _SCREAMING_SNAKE_CASE )), (("transformer", "wte", "embedding"), P('mp' , _SCREAMING_SNAKE_CASE )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(_SCREAMING_SNAKE_CASE , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , _SCREAMING_SNAKE_CASE )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(_SCREAMING_SNAKE_CASE , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , _SCREAMING_SNAKE_CASE )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _A = _get_partition_rules() _A = _replacement_rules(_SCREAMING_SNAKE_CASE ) _A = {k: _unmatched for k in flatten_dict(_SCREAMING_SNAKE_CASE )} _A = {k: replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(_SCREAMING_SNAKE_CASE ) )
27
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : str = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> YolosConfig: """simple docstring""" UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 UpperCAmelCase = [800, 1_333] UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase = 330 UpperCAmelCase = 14 UpperCAmelCase = 6 UpperCAmelCase = 1_320 elif "yolos_s" in yolos_name: UpperCAmelCase = 384 UpperCAmelCase = 1_536 UpperCAmelCase = 12 UpperCAmelCase = 6 elif "yolos_b" in yolos_name: UpperCAmelCase = [800, 1_344] UpperCAmelCase = 91 UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''coco-detection-id2label.json''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosConfig , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[: config.hidden_size, :] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __snake_case ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if "backbone" in name: UpperCAmelCase = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: UpperCAmelCase = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: UpperCAmelCase = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: UpperCAmelCase = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: UpperCAmelCase = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCAmelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: UpperCAmelCase = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCAmelCase = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCAmelCase = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCAmelCase = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCAmelCase = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCAmelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCAmelCase = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: UpperCAmelCase = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: UpperCAmelCase = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: UpperCAmelCase = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def __snake_case ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: UpperCAmelCase = key.split('''.''' ) UpperCAmelCase = int(key_split[2] ) UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase = val[:dim, :] UpperCAmelCase = val[ dim : dim * 2, : ] UpperCAmelCase = val[-dim:, :] else: UpperCAmelCase = val[:dim] UpperCAmelCase = val[dim : dim * 2] UpperCAmelCase = val[-dim:] else: UpperCAmelCase = val return orig_state_dict def __snake_case ( ) -> torch.Tensor: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : bool = False ) -> str: """simple docstring""" UpperCAmelCase = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' )['''model'''] # load 🤗 model UpperCAmelCase = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCAmelCase = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase = 800 if yolos_name != '''yolos_ti''' else 512 UpperCAmelCase = YolosImageProcessor(format='''coco_detection''' , size=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase, UpperCAmelCase = outputs.logits, outputs.pred_boxes UpperCAmelCase, UpperCAmelCase = None, None if yolos_name == "yolos_ti": UpperCAmelCase = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) UpperCAmelCase = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) UpperCAmelCase = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) UpperCAmelCase = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": UpperCAmelCase = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) UpperCAmelCase = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {yolos_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: UpperCAmelCase = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) model.push_to_hub(SCREAMING_SNAKE_CASE_ , organization='''hustvl''' ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.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.' ) a__ : Optional[Any] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
51
0
'''simple docstring''' def lowercase__( __UpperCamelCase: int ,__UpperCamelCase: int ): """simple docstring""" while a != 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = b % a, a return b def lowercase__( __UpperCamelCase: int ,__UpperCamelCase: int ): """simple docstring""" if gcd(__UpperCamelCase ,__UpperCamelCase ) != 1: SCREAMING_SNAKE_CASE : Tuple = f"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(__UpperCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 0, a SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 0, 1, m while va != 0: SCREAMING_SNAKE_CASE : Optional[Any] = ua // va SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
28
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType a__ : List[Any] = logging.get_logger(__name__) a__ : int = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off a__ : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] a__ : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase ="whisper" _lowerCamelCase =["past_key_values"] _lowerCamelCase ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[Any] , a__ : Any=51865 , a__ : Any=80 , a__ : Dict=6 , a__ : int=4 , a__ : int=6 , a__ : str=4 , a__ : int=1536 , a__ : Optional[Any]=1536 , a__ : str=0.0 , a__ : Optional[int]=0.0 , a__ : Optional[int]=50257 , a__ : int=True , a__ : Optional[int]=True , a__ : str="gelu" , a__ : List[str]=256 , a__ : Union[str, Any]=0.0 , a__ : List[str]=0.0 , a__ : Any=0.0 , a__ : str=0.02 , a__ : str=False , a__ : int=1500 , a__ : Tuple=448 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Optional[Any]=50256 , a__ : Tuple=None , a__ : List[Any]=[220, 50256] , a__ : Optional[int]=False , a__ : Optional[Any]=256 , a__ : Any=False , a__ : int=0.05 , a__ : Optional[Any]=10 , a__ : Dict=2 , a__ : Optional[Any]=0.0 , a__ : Tuple=10 , a__ : Any=0 , a__ : str=7 , **a__ : Any , ): UpperCAmelCase = vocab_size UpperCAmelCase = num_mel_bins UpperCAmelCase = d_model UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = max_source_positions UpperCAmelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size UpperCAmelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks UpperCAmelCase = median_filter_width super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , decoder_start_token_id=a__ , suppress_tokens=a__ , begin_suppress_tokens=a__ , **a__ , ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @property def __snake_case ( self : List[str] ): UpperCAmelCase = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: UpperCAmelCase = {0: '''batch'''} else: UpperCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs def __snake_case ( self : str , a__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a__ : int = -1 , a__ : int = -1 , a__ : bool = False , a__ : Optional["TensorType"] = None , a__ : int = 22050 , a__ : float = 5.0 , a__ : int = 220 , ): UpperCAmelCase = OrderedDict() UpperCAmelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a__ , framework=a__ , sampling_rate=a__ , time_duration=a__ , frequency=a__ , ) UpperCAmelCase = encoder_inputs['''input_features'''].shape[2] UpperCAmelCase = encoder_sequence_length // 2 if self.use_past else seq_length UpperCAmelCase = super().generate_dummy_inputs( preprocessor.tokenizer , a__ , a__ , a__ , a__ ) UpperCAmelCase = encoder_inputs.pop('''input_features''' ) UpperCAmelCase = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: UpperCAmelCase = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __snake_case ( self : Dict ): return 1e-3
51
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, ) A_ = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
29
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =LEDConfig _lowerCamelCase ={} _lowerCamelCase ="gelu" def __init__( self : Tuple , a__ : Any , a__ : int=13 , a__ : List[Any]=7 , a__ : int=True , a__ : Union[str, Any]=False , a__ : Tuple=99 , a__ : Any=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : List[Any]=37 , a__ : List[Any]=0.1 , a__ : Any=0.1 , a__ : Optional[int]=20 , a__ : List[Any]=2 , a__ : Union[str, Any]=1 , a__ : List[Any]=0 , a__ : Union[str, Any]=4 , ): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = eos_token_id UpperCAmelCase = pad_token_id UpperCAmelCase = bos_token_id UpperCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after UpperCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests UpperCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __snake_case ( self : Optional[int] ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) UpperCAmelCase = prepare_led_inputs_dict(a__ , a__ , a__ ) UpperCAmelCase = tf.concat( [tf.zeros_like(a__ )[:, :-1], tf.ones_like(a__ )[:, -1:]] , axis=-1 , ) UpperCAmelCase = global_attention_mask return config, inputs_dict def __snake_case ( self : Optional[int] , a__ : List[str] , a__ : int ): UpperCAmelCase = TFLEDModel(config=a__ ).get_decoder() UpperCAmelCase = inputs_dict['''input_ids'''] UpperCAmelCase = input_ids[:1, :] UpperCAmelCase = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase = 1 # first forward pass UpperCAmelCase = model(a__ , attention_mask=a__ , use_cache=a__ ) UpperCAmelCase, UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase = model(a__ , attention_mask=a__ )[0] UpperCAmelCase = model(a__ , attention_mask=a__ , past_key_values=a__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(a__ , a__ , rtol=1e-3 ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=None , ) -> Dict: """simple docstring""" if attention_mask is None: UpperCAmelCase = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowerCamelCase =(TFLEDForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase =( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =False _lowerCamelCase =False def __snake_case ( self : Optional[Any] ): UpperCAmelCase = TFLEDModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=a__ ) def __snake_case ( self : int ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*a__ ) def __snake_case ( self : Optional[int] ): UpperCAmelCase, UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = tf.zeros_like(inputs_dict['''attention_mask'''] ) UpperCAmelCase = 2 UpperCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , ) UpperCAmelCase = True UpperCAmelCase = self.model_tester.seq_length UpperCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(a__ : Tuple ): UpperCAmelCase = outputs.decoder_attentions self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(a__ : int ): UpperCAmelCase = [t.numpy() for t in outputs.encoder_attentions] UpperCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) UpperCAmelCase = len(a__ ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) if self.is_encoder_decoder: UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_decoder_attentions_output(a__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) # Check attention is always last and order is fine UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = model_class(a__ ) UpperCAmelCase = model(self._prepare_for_class(a__ , a__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) ) self.assertEqual(model.config.output_hidden_states , a__ ) check_encoder_attentions_output(a__ ) @unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' ) def __snake_case ( self : Any ): pass def __snake_case ( self : Union[str, Any] ): # TODO: Head-masking not yet implement pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> Tuple: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE_ , dtype=tf.intaa ) a__ : int = 1e-4 @slow @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, 768) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 ) def __snake_case ( self : str ): UpperCAmelCase = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ) # change to intended input here UpperCAmelCase = _long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = _long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]] ) UpperCAmelCase = prepare_led_inputs_dict(model.config , a__ , a__ ) UpperCAmelCase = model(**a__ )[0] UpperCAmelCase = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , a__ ) # change to expected output here UpperCAmelCase = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1e-3 , rtol=1e-3 )
51
0
from __future__ import annotations from math import pow, sqrt def lowerCamelCase__ ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance == 0: return {"resistance": sqrt(pow(_lowercase , 2 ) - pow(_lowercase , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_lowercase , 2 ) - pow(_lowercase , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_lowercase , 2 ) + pow(_lowercase , 2 ) )} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
30
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : List[Any] = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
51
0
def UpperCAmelCase_ ( __UpperCAmelCase : list , __UpperCAmelCase : list ) -> float: _validate_point(__UpperCAmelCase ) _validate_point(__UpperCAmelCase ) if len(__UpperCAmelCase ) != len(__UpperCAmelCase ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(a - b ) for a, b in zip(__UpperCAmelCase , __UpperCAmelCase ) ) ) def UpperCAmelCase_ ( __UpperCAmelCase : list[float] ) -> None: if point: if isinstance(__UpperCAmelCase , __UpperCAmelCase ): for item in point: if not isinstance(__UpperCAmelCase , (int, float) ): SCREAMING_SNAKE_CASE_ = ( 'Expected a list of numbers as input, found ' f"{type(__UpperCAmelCase ).__name__}" ) raise TypeError(__UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_ = f"Expected a list of numbers as input, found {type(__UpperCAmelCase ).__name__}" raise TypeError(__UpperCAmelCase ) else: raise ValueError('Missing an input' ) def UpperCAmelCase_ ( __UpperCAmelCase : list , __UpperCAmelCase : list ) -> float: _validate_point(__UpperCAmelCase ) _validate_point(__UpperCAmelCase ) if len(__UpperCAmelCase ) != len(__UpperCAmelCase ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(x - y ) for x, y in zip(__UpperCAmelCase , __UpperCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
31
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a__ : List[Any] = 'sshleifer/mar_enro_6_3_student' class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __snake_case ( self : Dict ): super().setUp() UpperCAmelCase = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=a__ , ) UpperCAmelCase = f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def __snake_case ( self : Optional[int] ): MarianMTModel.from_pretrained(a__ ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script UpperCAmelCase = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") UpperCAmelCase = f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future UpperCAmelCase = ['''finetune.py'''] + bash_script.split() + args with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationModule.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Any ): UpperCAmelCase = f"{self.test_file_dir_str}/test_data/wmt_en_ro" UpperCAmelCase = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 128, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script UpperCAmelCase = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) UpperCAmelCase = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) UpperCAmelCase = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): UpperCAmelCase = bash_script.replace(a__ , str(a__ ) ) UpperCAmelCase = self.get_auto_remove_tmp_dir() UpperCAmelCase = bash_script.replace('''--fp16''' , '''''' ) UpperCAmelCase = 6 UpperCAmelCase = ( ['''distillation.py'''] + bash_script.split() + [ f"--output_dir={output_dir}", '''--gpus=1''', '''--learning_rate=1e-3''', f"--num_train_epochs={epochs}", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(a__ , '''argv''' , a__ ): UpperCAmelCase = argparse.ArgumentParser() UpperCAmelCase = pl.Trainer.add_argparse_args(a__ ) UpperCAmelCase = SummarizationDistiller.add_model_specific_args(a__ , os.getcwd() ) UpperCAmelCase = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu UpperCAmelCase = distill_main(a__ ) # Check metrics UpperCAmelCase = load_json(model.metrics_save_path ) UpperCAmelCase = metrics['''val'''][0] UpperCAmelCase = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , a__ ) # check lightning ckpt can be loaded and has a reasonable statedict UpperCAmelCase = os.listdir(a__ ) UpperCAmelCase = [x for x in contents if x.endswith('''.ckpt''' )][0] UpperCAmelCase = os.path.join(args.output_dir , a__ ) UpperCAmelCase = torch.load(a__ , map_location='''cpu''' ) UpperCAmelCase = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: UpperCAmelCase = {os.path.basename(a__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
51
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __UpperCamelCase ( A__ , A__ ): __A : Union[str, Any] = """focalnet""" def __init__( self , _UpperCamelCase=224 , _UpperCamelCase=4 , _UpperCamelCase=3 , _UpperCamelCase=96 , _UpperCamelCase=False , _UpperCamelCase=[192, 384, 768, 768] , _UpperCamelCase=[2, 2, 6, 2] , _UpperCamelCase=[2, 2, 2, 2] , _UpperCamelCase=[3, 3, 3, 3] , _UpperCamelCase="gelu" , _UpperCamelCase=4.0 , _UpperCamelCase=0.0 , _UpperCamelCase=0.1 , _UpperCamelCase=False , _UpperCamelCase=1e-4 , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=0.02 , _UpperCamelCase=1e-5 , _UpperCamelCase=32 , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase , ): super().__init__(**_UpperCamelCase ) _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = use_conv_embed _UpperCAmelCase = hidden_sizes _UpperCAmelCase = depths _UpperCAmelCase = focal_levels _UpperCAmelCase = focal_windows _UpperCAmelCase = hidden_act _UpperCAmelCase = mlp_ratio _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = use_layerscale _UpperCAmelCase = layerscale_value _UpperCAmelCase = use_post_layernorm _UpperCAmelCase = use_post_layernorm_in_modulation _UpperCAmelCase = normalize_modulator _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = encoder_stride _UpperCAmelCase = ['''stem'''] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices( out_features=_UpperCamelCase , out_indices=_UpperCamelCase , stage_names=self.stage_names )
32
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["image_processor", "tokenizer"] _lowerCamelCase ="CLIPImageProcessor" _lowerCamelCase =("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : Union[str, Any] , a__ : List[str]=None , a__ : Union[str, Any]=None , **a__ : Optional[Any] ): UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a__ , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a__ , a__ ) def __call__( self : Any , a__ : Any=None , a__ : str=None , a__ : List[Any]=None , **a__ : List[str] ): 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: UpperCAmelCase = self.tokenizer(a__ , return_tensors=a__ , **a__ ) if images is not None: UpperCAmelCase = self.image_processor(a__ , return_tensors=a__ , **a__ ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a__ ) , tensor_type=a__ ) def __snake_case ( self : Optional[Any] , *a__ : int , **a__ : List[Any] ): return self.tokenizer.batch_decode(*a__ , **a__ ) def __snake_case ( self : Any , *a__ : Union[str, Any] , **a__ : Any ): return self.tokenizer.decode(*a__ , **a__ ) @property def __snake_case ( self : Union[str, Any] ): UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
51
0
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> int: snake_case__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def SCREAMING_SNAKE_CASE ( __lowerCAmelCase = 100 ) -> int: snake_case__ = 1 snake_case__ = 2 for i in range(2 , max_n + 1 ): snake_case__ = pre_numerator snake_case__ = 2 * i // 3 if i % 3 == 0 else 1 snake_case__ = cur_numerator snake_case__ = e_cont * pre_numerator + temp return sum_digits(__lowerCAmelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
33
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
51
0
"""simple docstring""" import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from transformers.testing_utils import require_phonemizer from ...test_tokenization_common import TokenizerTesterMixin @require_phonemizer class snake_case_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" A_ = WavaVecaPhonemeCTCTokenizer A_ = False def UpperCAmelCase__ ( self) -> List[str]: super().setUp() UpperCamelCase = ( '''<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː ''' '''ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː ''' '''ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 ''' '''oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ ''' '''pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ ''' '''yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ ''' '''əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ ''' '''ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ ''' '''ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ ''' '''uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ ''' '''ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ ''' '''ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ ''' '''ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4''' ).split(''' ''') UpperCamelCase = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_)))) UpperCamelCase = {'''pad_token''': '''<pad>''', '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>'''} UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as fp: fp.write(json.dumps(lowerCamelCase_) + '''\n''') def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_=False , lowerCamelCase_=2_0 , lowerCamelCase_=5) -> Tuple[str, list]: UpperCamelCase = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=lowerCamelCase_)) for i in range(len(lowerCamelCase_))] UpperCamelCase = list(filter(lambda lowerCamelCase_: [t[0]] == tokenizer.encode(t[1] , do_phonemize=lowerCamelCase_) , lowerCamelCase_)) if max_length is not None and len(lowerCamelCase_) > max_length: UpperCamelCase = toks[:max_length] if min_length is not None and len(lowerCamelCase_) < min_length and len(lowerCamelCase_) > 0: while len(lowerCamelCase_) < min_length: UpperCamelCase = toks + toks # toks_str = [t[1] for t in toks] UpperCamelCase = [t[0] for t in toks] # Ensure consistency UpperCamelCase = tokenizer.decode(lowerCamelCase_ , clean_up_tokenization_spaces=lowerCamelCase_) if " " not in output_txt and len(lowerCamelCase_) > 1: UpperCamelCase = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=lowerCamelCase_) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=lowerCamelCase_) ) if with_prefix_space: UpperCamelCase = ''' ''' + output_txt UpperCamelCase = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_) return output_txt, output_ids def UpperCAmelCase__ ( self , **lowerCamelCase_) -> Optional[int]: kwargs.update(self.special_tokens_map) return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase_) def UpperCAmelCase__ ( self) -> Dict: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') # check adding a single token tokenizer.add_tokens('''xxx''') UpperCamelCase = tokenizer('''m xxx ɪ''' , do_phonemize=lowerCamelCase_).input_ids self.assertEqual(lowerCamelCase_ , [1_3, 3_9_2, 1_7]) # xxx should be last token tokenizer.add_tokens(['''aaa''', '''bbb''', '''ccc''']) UpperCamelCase = tokenizer('''m aaa ɪ ccc''' , do_phonemize=lowerCamelCase_).input_ids self.assertEqual(lowerCamelCase_ , [1_3, 3_9_3, 1_7, 3_9_5]) # aaa and ccc should be after xxx and 2 after aaa UpperCamelCase = tokenizer('''maɪ c''' , do_phonemize=lowerCamelCase_).input_ids self.assertEqual(lowerCamelCase_ , [3, 2_0_0]) # mai should be <unk> (=3) def UpperCAmelCase__ ( self) -> str: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') self.assertEqual(lowerCamelCase_ , '''h ə l oʊ h aʊ ɑːɹ j uː''') def UpperCAmelCase__ ( self) -> Any: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') self.assertEqual(tokenizer(lowerCamelCase_).input_ids , tokenizer(lowerCamelCase_ , do_phonemize=lowerCamelCase_).input_ids) def UpperCAmelCase__ ( self) -> str: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') UpperCamelCase = tokenizer.decode(tokenizer(lowerCamelCase_).input_ids) self.assertEqual(lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self) -> str: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') UpperCamelCase = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7], ] UpperCamelCase = tokenizer.decode(sample_ids[0]) UpperCamelCase = tokenizer.batch_decode(lowerCamelCase_) self.assertEqual(lowerCamelCase_ , batch_tokens[0]) self.assertEqual(lowerCamelCase_ , ['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ''']) def UpperCAmelCase__ ( self) -> Optional[int]: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''') tokenizer.add_tokens('''|''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') self.assertEqual(lowerCamelCase_ , '''h ə l oʊ | h aʊ | ɑːɹ | j uː |''') def UpperCAmelCase__ ( self) -> Any: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''') tokenizer.add_tokens('''|''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') self.assertEqual(tokenizer(lowerCamelCase_).input_ids , tokenizer(lowerCamelCase_ , do_phonemize=lowerCamelCase_).input_ids) def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''') tokenizer.add_tokens('''|''') # fmt: off UpperCamelCase = [ [1_1, 5, 1_5, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 1_5, 8, tokenizer.word_delimiter_token_id, 9_8], [tokenizer.word_delimiter_token_id, 2_4, 2_2, tokenizer.word_delimiter_token_id, 5, 2_4, 2_2, 5, 7_7], ] # fmt: on # decode with word_del_token filter UpperCamelCase = tokenizer.decode(sample_ids[0]) UpperCamelCase = tokenizer.batch_decode(lowerCamelCase_) self.assertEqual(lowerCamelCase_ , batch_tokens[0]) self.assertEqual(lowerCamelCase_ , ['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ''']) # decode with no word_del_token filter UpperCamelCase = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=lowerCamelCase_) UpperCamelCase = tokenizer.batch_decode(lowerCamelCase_ , filter_word_delimiter_token=lowerCamelCase_) self.assertEqual(lowerCamelCase_ , batch_tokens[0]) self.assertEqual(lowerCamelCase_ , ['''k s ɾ | ɾ l | ɭʲ''', '''| j ð | s j ð s oːɹ''']) def UpperCAmelCase__ ( self) -> Dict: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''') tokenizer.add_tokens('''|''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') UpperCamelCase = tokenizer.decode(tokenizer(lowerCamelCase_).input_ids , filter_word_delimiter_token=lowerCamelCase_) self.assertEqual(lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self) -> int: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''') tokenizer.add_tokens('''|''') UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer.phonemize(lowerCamelCase_ , phonemizer_lang='''en-us''') UpperCamelCase = tokenizer.decode(tokenizer(lowerCamelCase_).input_ids , filter_word_delimiter_token=lowerCamelCase_) self.assertEqual(''' '''.join([p.strip() for p in phonemes.split(''' |''')]).strip() , lowerCamelCase_) def UpperCAmelCase__ ( self) -> int: UpperCamelCase = self.tokenizer_class.from_pretrained( '''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token=lowerCamelCase_) UpperCamelCase = '''Hello how are you''' UpperCamelCase = tokenizer(lowerCamelCase_ , phonemizer_lang='''en-us''').input_ids UpperCamelCase = tokenizer(lowerCamelCase_ , phonemizer_lang='''fr-fr''').input_ids self.assertNotEqual(lowerCamelCase_ , lowerCamelCase_) UpperCamelCase = tokenizer.decode(lowerCamelCase_) UpperCamelCase = tokenizer.decode(lowerCamelCase_) self.assertEqual(lowerCamelCase_ , '''h ə l oʊ h aʊ ɑːɹ j uː''') self.assertEqual(lowerCamelCase_ , '''ɛ l o h aʊ a ʁ j u''') def UpperCAmelCase__ ( self) -> Any: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') UpperCamelCase = '''Hello how Are you''' UpperCamelCase = '''hello how are you''' UpperCamelCase = tokenizer(lowerCamelCase_).input_ids UpperCamelCase = tokenizer(lowerCamelCase_).input_ids self.assertEqual(lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self) -> List[Any]: UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''') tokenizer.add_tokens(['''!''', '''?''']) tokenizer.add_special_tokens({'''cls_token''': '''$$$'''}) # fmt: off UpperCamelCase = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8, 3_9_2, 3_9_2, 3_9_3, 3_9_2, 3_9_2, 3_9_3, 3_9_4, 3_9_4], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7, tokenizer.pad_token_id, 3_9_4, 3_9_4], ] # fmt: on UpperCamelCase = tokenizer.batch_decode(lowerCamelCase_) self.assertEqual(lowerCamelCase_ , ['''k s ɾ ɾ l ɭʲ!?!? $$$''', '''j ð s j ð s oːɹ $$$''']) @staticmethod def UpperCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_) -> List[str]: UpperCamelCase = [d[key] for d in offsets] return retrieved_list def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = self.get_tokenizer(word_delimiter_token='''|''') tokenizer.add_tokens('''|''') # fmt: off # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" UpperCamelCase = [1_1, 5, 5, 5, 1_5, 1_5, tokenizer.pad_token_id, 1_5, 1_5, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 1_5, 8, 8, 8, tokenizer.word_delimiter_token_id, 9_8] # fmt: on UpperCamelCase = tokenizer.decode(lowerCamelCase_ , output_char_offsets=lowerCamelCase_ , filter_word_delimiter_token=lowerCamelCase_) # check Wav2Vec2CTCTokenizerOutput keys for char self.assertEqual(len(outputs.keys()) , 2) self.assertTrue('''text''' in outputs) self.assertTrue('''char_offsets''' in outputs) self.assertTrue(isinstance(lowerCamelCase_ , lowerCamelCase_)) # check that order of chars is correct and identical for both outputs self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''char_offsets'''] , '''char''')) , outputs.text) self.assertListEqual( self.get_from_offsets(outputs['''char_offsets'''] , '''char''') , ['''k''', '''s''', '''ɾ''', '''ɾ''', '''|''', '''ɾ''', '''l''', '''|''', '''ɭʲ''']) # check that offsets are actually correct for char # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 self.assertListEqual( self.get_from_offsets(outputs['''char_offsets'''] , '''start_offset''') , [0, 1, 4, 7, 9, 1_1, 1_2, 1_5, 1_6]) self.assertListEqual( self.get_from_offsets(outputs['''char_offsets'''] , '''end_offset''') , [1, 4, 6, 9, 1_0, 1_2, 1_5, 1_6, 1_7]) def UpperCAmelCase__ ( self) -> Any: UpperCamelCase = self.get_tokenizer(word_delimiter_token='''|''') def check_list_tuples_equal(lowerCamelCase_ , lowerCamelCase_): self.assertTrue(isinstance(lowerCamelCase_ , lowerCamelCase_)) self.assertTrue(isinstance(outputs_list[0] , lowerCamelCase_)) # transform list to ModelOutput UpperCamelCase = WavaVecaPhonemeCTCTokenizerOutput( {k: [d[k] for d in outputs_list] for k in outputs_list[0]}) self.assertListEqual(outputs_batch['''text'''] , outputs_batch_a['''text''']) def recursive_check(lowerCamelCase_ , lowerCamelCase_): if isinstance(lowerCamelCase_ , lowerCamelCase_): [recursive_check(lowerCamelCase_ , lowerCamelCase_) for la, la in zip(lowerCamelCase_ , lowerCamelCase_)] self.assertEqual(lowerCamelCase_ , lowerCamelCase_) if "char_offsets" in outputs_batch: recursive_check(outputs_batch['''char_offsets'''] , outputs_batch_a['''char_offsets''']) # fmt: off UpperCamelCase = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 4, 8, 9_8, 3_2, 3_2, 3_2, 3_2, 4, 3_3, tokenizer.word_delimiter_token_id, 3_2, 3_2, 3_3, 3_4, 3_4], [2_4, 2_2, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 2_4, 2_2, 2_2, 2_2, 4, 5, 7_7, tokenizer.pad_token_id, 2_2, 2_2, 4, 3_4, 3_4, 3_4, 3_4], ] # fmt: on # We assume that `decode` works as expected. All we will check now is # the output type is correct and the output is identical to `decode` # char UpperCamelCase = tokenizer.batch_decode(lowerCamelCase_ , output_char_offsets=lowerCamelCase_) UpperCamelCase = [tokenizer.decode(lowerCamelCase_ , output_char_offsets=lowerCamelCase_) for ids in sample_ids] check_list_tuples_equal(lowerCamelCase_ , lowerCamelCase_) @unittest.skip('''Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes''') def UpperCAmelCase__ ( self) -> Tuple: pass @unittest.skip('''Wav2Vec2PhonemeTokenizer always puts spaces between phonemes''') def UpperCAmelCase__ ( self) -> Dict: pass @unittest.skip('''encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency''') def UpperCAmelCase__ ( self) -> int: pass @unittest.skip('''Wav2Vec2PhonemeModel has no max model length => no testing''') def UpperCAmelCase__ ( self) -> Tuple: pass def UpperCAmelCase__ ( self) -> Tuple: UpperCamelCase = self.get_tokenizers(do_lower_case=lowerCamelCase_) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}'): UpperCamelCase = tokenizer.vocab_size UpperCamelCase = len(lowerCamelCase_) self.assertNotEqual(lowerCamelCase_ , 0) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) UpperCamelCase = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] UpperCamelCase = tokenizer.add_tokens(lowerCamelCase_) UpperCamelCase = tokenizer.vocab_size UpperCamelCase = len(lowerCamelCase_) self.assertNotEqual(lowerCamelCase_ , 0) self.assertEqual(lowerCamelCase_ , lowerCamelCase_) self.assertEqual(lowerCamelCase_ , len(lowerCamelCase_)) self.assertEqual(lowerCamelCase_ , all_size + len(lowerCamelCase_)) UpperCamelCase = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=lowerCamelCase_) self.assertGreaterEqual(len(lowerCamelCase_) , 4) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) UpperCamelCase = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} UpperCamelCase = tokenizer.add_special_tokens(lowerCamelCase_) UpperCamelCase = tokenizer.vocab_size UpperCamelCase = len(lowerCamelCase_) self.assertNotEqual(lowerCamelCase_ , 0) self.assertEqual(lowerCamelCase_ , lowerCamelCase_) self.assertEqual(lowerCamelCase_ , len(lowerCamelCase_)) self.assertEqual(lowerCamelCase_ , all_size_a + len(lowerCamelCase_)) UpperCamelCase = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=lowerCamelCase_) self.assertGreaterEqual(len(lowerCamelCase_) , 6) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[0] , tokens[1]) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokens[-4]) self.assertEqual(tokens[0] , tokenizer.eos_token_id) self.assertEqual(tokens[-3] , tokenizer.pad_token_id) @unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.''') def UpperCAmelCase__ ( self) -> Tuple: pass @unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.''') def UpperCAmelCase__ ( self) -> Optional[int]: pass def UpperCAmelCase__ ( self) -> Optional[Any]: # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which # is not the case for Wav2Vec2PhonemeCTCTokenizer. UpperCamelCase = self.get_tokenizers(fast=lowerCamelCase_ , do_lower_case=lowerCamelCase_) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}'): UpperCamelCase = ['''ð''', '''ɪ''', '''s''', '''ɪ''', '''z''', '''ɐ''', '''t''', '''ɛ''', '''k''', '''s''', '''t'''] UpperCamelCase = tokenizer.convert_tokens_to_string(lowerCamelCase_) self.assertIsInstance(output['''text'''] , lowerCamelCase_)
34
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ): pass def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str: """simple docstring""" UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict: """simple docstring""" UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase =dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _lowerCamelCase =dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ): UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __snake_case ( self : int , a__ : Dict , a__ : Tuple ): pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __snake_case ( self : str ): pass @slow @require_torch def __snake_case ( self : Optional[Any] ): UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __snake_case ( self : Dict ): UpperCAmelCase = '''facebook/sam-vit-huge''' UpperCAmelCase = pipeline('''mask-generation''' , model=a__ ) UpperCAmelCase = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCAmelCase = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053}, ] , )
51
0
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase ( _UpperCAmelCase , unittest.TestCase ): lowerCamelCase : Any = RobertaTokenizer lowerCamelCase : List[Any] = RobertaTokenizerFast lowerCamelCase : Optional[Any] = True lowerCamelCase : Optional[Any] = {'''cls_token''': '''<s>'''} def lowercase__ ( self : Optional[int] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : List[str] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE__ : List[str] = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE__ : Tuple = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_lowercase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_lowercase ) ) def lowercase__ ( self : str , **_lowercase : str ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowercase__ ( self : Any , **_lowercase : str ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **_lowercase ) def lowercase__ ( self : Union[str, Any] , _lowercase : List[str] ): SCREAMING_SNAKE_CASE__ : Optional[Any] = '''lower newer''' SCREAMING_SNAKE_CASE__ : Optional[int] = '''lower newer''' return input_text, output_text def lowercase__ ( self : Dict ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''lower newer''' SCREAMING_SNAKE_CASE__ : List[Any] = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.tokenize(_lowercase ) # , add_prefix_space=True) self.assertListEqual(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : List[str] = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase ) , _lowercase ) def lowercase__ ( self : Dict ): SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' , add_special_tokens=_lowercase ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' , add_special_tokens=_lowercase ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def lowercase__ ( self : List[str] ): SCREAMING_SNAKE_CASE__ : int = self.tokenizer_class.from_pretrained('''roberta-base''' ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode('''sequence builders''' , add_special_tokens=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode( '''sequence builders''' , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_lowercase , _lowercase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def lowercase__ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = '''Encode this sequence.''' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments SCREAMING_SNAKE_CASE__ : int = tokenizer.encode(_lowercase , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.encode(_lowercase , add_special_tokens=_lowercase , add_prefix_space=_lowercase ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(_lowercase , _lowercase ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(_lowercase , _lowercase ) # Testing spaces after special tokens SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(_lowercase , lstrip=_lowercase , rstrip=_lowercase )} ) # mask token has a left space SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowercase ) SCREAMING_SNAKE_CASE__ : List[str] = '''Encode <mask> sequence''' SCREAMING_SNAKE_CASE__ : List[Any] = '''Encode <mask>sequence''' SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode(_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = encoded.index(_lowercase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(_lowercase ) SCREAMING_SNAKE_CASE__ : Tuple = encoded.index(_lowercase ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(_lowercase , _lowercase ) def lowercase__ ( self : Tuple ): pass def lowercase__ ( self : int ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE__ : List[str] = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) SCREAMING_SNAKE_CASE__ : Dict = '''A, <mask> AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) SCREAMING_SNAKE_CASE__ : int = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( _lowercase , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( _lowercase , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def lowercase__ ( self : Any ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): SCREAMING_SNAKE_CASE__ : List[Any] = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) SCREAMING_SNAKE_CASE__ : List[str] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] , _lowercase ) self.assertEqual(post_processor_state['''add_prefix_space'''] , _lowercase ) self.assertEqual(post_processor_state['''trim_offsets'''] , _lowercase ) def lowercase__ ( self : Optional[int] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE__ : Tuple = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE__ : int = f"""{text_of_1_token} {text_of_1_token}""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ) + 1, len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : List[str] = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ) + 1, len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : Dict = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ), len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowercase ), len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : str = f""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) SCREAMING_SNAKE_CASE__ : List[Any] = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : int = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ) + 1, 1 + len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : str = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ), 1 + len(_lowercase ) + 1 + len(_lowercase )) , ) SCREAMING_SNAKE_CASE__ : Tuple = self.rust_tokenizer_class.from_pretrained( _lowercase , use_fast=_lowercase , add_prefix_space=_lowercase , trim_offsets=_lowercase ) SCREAMING_SNAKE_CASE__ : str = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_lowercase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowercase ), 1 + len(_lowercase ) + 1 + len(_lowercase )) , )
35
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(SCREAMING_SNAKE_CASE_ ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =["pixel_values"] def __init__( self : int , a__ : bool = True , a__ : Dict[str, int] = None , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : bool = True , a__ : Dict[str, int] = None , a__ : bool = True , a__ : Union[int, float] = 1 / 255 , a__ : bool = True , a__ : bool = True , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , **a__ : Union[str, Any] , ): super().__init__(**a__ ) UpperCAmelCase = size if size is not None else {'''shortest_edge''': 256} UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_center_crop UpperCAmelCase = crop_size UpperCAmelCase = resample UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = offset UpperCAmelCase = do_normalize UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __snake_case ( self : Dict , a__ : np.ndarray , a__ : Dict[str, int] , a__ : PILImageResampling = PILImageResampling.BILINEAR , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Optional[int] , ): UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) if "shortest_edge" in size: UpperCAmelCase = get_resize_output_image_size(a__ , size['''shortest_edge'''] , default_to_square=a__ ) elif "height" in size and "width" in size: UpperCAmelCase = (size['''height'''], size['''width''']) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a__ , size=a__ , resample=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Union[str, Any] , a__ : np.ndarray , a__ : Dict[str, int] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): UpperCAmelCase = get_size_dict(a__ ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a__ , size=(size['''height'''], size['''width''']) , data_format=a__ , **a__ ) def __snake_case ( self : List[str] , a__ : np.ndarray , a__ : Union[int, float] , a__ : bool = True , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Dict , ): UpperCAmelCase = image.astype(np.floataa ) if offset: UpperCAmelCase = image - (scale / 2) return rescale(a__ , scale=a__ , data_format=a__ , **a__ ) def __snake_case ( self : int , a__ : np.ndarray , a__ : Union[float, List[float]] , a__ : Union[float, List[float]] , a__ : Optional[Union[str, ChannelDimension]] = None , **a__ : Any , ): return normalize(a__ , mean=a__ , std=a__ , data_format=a__ , **a__ ) def __snake_case ( self : Any , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. UpperCAmelCase = to_numpy_array(a__ ) if do_resize: UpperCAmelCase = self.resize(image=a__ , size=a__ , resample=a__ ) if do_center_crop: UpperCAmelCase = self.center_crop(a__ , size=a__ ) if do_rescale: UpperCAmelCase = self.rescale(image=a__ , scale=a__ , offset=a__ ) if do_normalize: UpperCAmelCase = self.normalize(image=a__ , mean=a__ , std=a__ ) UpperCAmelCase = to_channel_dimension_format(a__ , a__ ) return image def __snake_case ( self : List[Any] , a__ : ImageInput , a__ : bool = None , a__ : Dict[str, int] = None , a__ : PILImageResampling = None , a__ : bool = None , a__ : Dict[str, int] = None , a__ : bool = None , a__ : float = None , a__ : bool = None , a__ : bool = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[float, List[float]]] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : ChannelDimension = ChannelDimension.FIRST , **a__ : Any , ): UpperCAmelCase = do_resize if do_resize is not None else self.do_resize UpperCAmelCase = resample if resample is not None else self.resample UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase = offset if offset is not None else self.offset UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase = image_mean if image_mean is not None else self.image_mean UpperCAmelCase = image_std if image_std is not None else self.image_std UpperCAmelCase = size if size is not None else self.size UpperCAmelCase = get_size_dict(a__ , default_to_square=a__ ) UpperCAmelCase = crop_size if crop_size is not None else self.crop_size UpperCAmelCase = get_size_dict(a__ , param_name='''crop_size''' ) if not valid_images(a__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) UpperCAmelCase = make_batched(a__ ) UpperCAmelCase = [ [ self._preprocess_image( image=a__ , do_resize=a__ , size=a__ , resample=a__ , do_center_crop=a__ , crop_size=a__ , do_rescale=a__ , rescale_factor=a__ , offset=a__ , do_normalize=a__ , image_mean=a__ , image_std=a__ , data_format=a__ , ) for img in video ] for video in videos ] UpperCAmelCase = {'''pixel_values''': videos} return BatchFeature(data=a__ , tensor_type=a__ )
51
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase : Dict = { '''configuration_instructblip''': [ '''INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InstructBlipConfig''', '''InstructBlipQFormerConfig''', '''InstructBlipVisionConfig''', ], '''processing_instructblip''': ['''InstructBlipProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[int] = [ '''INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InstructBlipQFormerModel''', '''InstructBlipPreTrainedModel''', '''InstructBlipForConditionalGeneration''', '''InstructBlipVisionModel''', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __lowercase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
36
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , a__ : List[str]="sayef/fsner-bert-base-uncased" ): super(a__ , self ).__init__() UpperCAmelCase = AutoModel.from_pretrained(a__ , return_dict=a__ ) UpperCAmelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCAmelCase = torch.nn.Softmax(dim=1 ) def __snake_case ( self : List[Any] , **a__ : Tuple ): return self.bert(**a__ ).last_hidden_state def __snake_case ( self : int , a__ : List[str] ): return token_embeddings.sum(2 , keepdim=a__ ) def __snake_case ( self : str , a__ : str , a__ : str , a__ : int=1 ): return self.softmax(T * self.cos(a__ , a__ ) ) def __snake_case ( self : Tuple , a__ : Tuple , a__ : str ): UpperCAmelCase = W_supports['''sizes'''].tolist() UpperCAmelCase = W_supports['''start_token_id'''].item() UpperCAmelCase = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = self.BERT(**a__ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = W_supports['''input_ids'''] == start_token_id UpperCAmelCase = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(a__ ): if i == 0: UpperCAmelCase = 0 else: UpperCAmelCase = support_sizes[i - 1] UpperCAmelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase = torch.vstack((p_starts, p_start) ) UpperCAmelCase = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase = p_start UpperCAmelCase = p_end return p_starts, p_ends
51
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCamelCase : List[str] = logging.get_logger(__name__) UpperCamelCase : Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCamelCase : str = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCamelCase : Optional[int] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class A__ ( A__ ): """simple docstring""" _lowercase = VOCAB_FILES_NAMES _lowercase = PRETRAINED_VOCAB_FILES_MAP _lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase = ['input_ids', 'attention_mask'] _lowercase = GPTaTokenizer def __init__( self : Optional[Any] , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Any="<|endoftext|>" , lowerCamelCase__ : Dict="<|endoftext|>" , lowerCamelCase__ : Tuple="<|endoftext|>" , lowerCamelCase__ : str=False , **lowerCamelCase__ : Any , ): super().__init__( lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , unk_token=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , **lowerCamelCase__ , ) a__ : Dict = kwargs.pop("add_bos_token" , lowerCamelCase__ ) a__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space: a__ : Optional[int] = getattr(lowerCamelCase__ , pre_tok_state.pop("type" ) ) a__ : List[str] = add_prefix_space a__ : Union[str, Any] = pre_tok_class(**lowerCamelCase__ ) a__ : int = add_prefix_space def _UpperCamelCase( self : Union[str, Any] , *lowerCamelCase__ : Union[str, Any] , **lowerCamelCase__ : Optional[int] ): a__ : str = kwargs.get("is_split_into_words" , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] , *lowerCamelCase__ : int , **lowerCamelCase__ : Optional[Any] ): a__ : Any = kwargs.get("is_split_into_words" , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : Optional[str] = None ): a__ : List[str] = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ ) def _UpperCamelCase( self : Any , lowerCamelCase__ : "Conversation" ): a__ : Tuple = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) + [self.eos_token_id] ) if len(lowerCamelCase__ ) > self.model_max_length: a__ : Optional[int] = input_ids[-self.model_max_length :] return input_ids
37
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' _lowerCamelCase =(EulerDiscreteScheduler,) _lowerCamelCase =10 def __snake_case ( self : str , **a__ : Tuple ): UpperCAmelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**a__ ) return config def __snake_case ( self : Dict ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a__ ) def __snake_case ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a__ , beta_end=a__ ) def __snake_case ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a__ ) def __snake_case ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def __snake_case ( self : Tuple ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma UpperCAmelCase = sample.to(a__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def __snake_case ( self : Optional[int] ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1e-2 assert abs(result_mean.item() - 0.0_131 ) < 1e-3 def __snake_case ( self : str ): UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**a__ , use_karras_sigmas=a__ ) scheduler.set_timesteps(self.num_inference_steps , device=a__ ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() UpperCAmelCase = sample.to(a__ ) for t in scheduler.timesteps: UpperCAmelCase = scheduler.scale_model_input(a__ , a__ ) UpperCAmelCase = model(a__ , a__ ) UpperCAmelCase = scheduler.step(a__ , a__ , a__ , generator=a__ ) UpperCAmelCase = output.prev_sample UpperCAmelCase = torch.sum(torch.abs(a__ ) ) UpperCAmelCase = torch.mean(torch.abs(a__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
51
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : Dict = logging.get_logger(__name__) A_ : List[str] = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''roc_bert''' def __init__( self , __SCREAMING_SNAKE_CASE=3_0_5_2_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=3_0_7_2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=9_1_0 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2_4_8_5_8 , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): snake_case__ : List[str] = vocab_size snake_case__ : Optional[Any] = max_position_embeddings snake_case__ : Optional[int] = hidden_size snake_case__ : Dict = num_hidden_layers snake_case__ : Optional[int] = num_attention_heads snake_case__ : str = intermediate_size snake_case__ : List[str] = hidden_act snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Optional[int] = initializer_range snake_case__ : Any = type_vocab_size snake_case__ : Dict = layer_norm_eps snake_case__ : Optional[Any] = use_cache snake_case__ : List[Any] = enable_pronunciation snake_case__ : Tuple = enable_shape snake_case__ : List[str] = pronunciation_embed_dim snake_case__ : List[str] = pronunciation_vocab_size snake_case__ : int = shape_embed_dim snake_case__ : Dict = shape_vocab_size snake_case__ : int = concat_input snake_case__ : Optional[int] = position_embedding_type snake_case__ : int = classifier_dropout super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : int=None ) -> Any: """simple docstring""" return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ ) @dataclass class lowerCAmelCase__ : '''simple docstring''' _lowerCamelCase =field( metadata={"help": "The csv file to plot."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Disable logarithmic scale when plotting"} , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={ "help": "Whether the csv file has training results or inference results. Defaults to inference results." } , ) _lowerCamelCase =field( default=UpperCAmelCase_ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , ) _lowerCamelCase =list_field( default=UpperCAmelCase_ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} ) def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: """simple docstring""" try: int(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False def __snake_case ( SCREAMING_SNAKE_CASE_ : Any ) -> str: """simple docstring""" try: float(SCREAMING_SNAKE_CASE_ ) return True except ValueError: return False class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict , a__ : Optional[int] ): UpperCAmelCase = args UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: UpperCAmelCase = csv.DictReader(a__ ) for row in reader: UpperCAmelCase = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None UpperCAmelCase = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None UpperCAmelCase = float(row['''result'''] ) def __snake_case ( self : Dict ): UpperCAmelCase, UpperCAmelCase = plt.subplots() UpperCAmelCase = '''Time usage''' if self.args.is_time else '''Memory usage''' UpperCAmelCase = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): UpperCAmelCase = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) UpperCAmelCase = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) UpperCAmelCase = self.result_dict[model_name]['''result'''] ((UpperCAmelCase), (UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=a__ , ) else: UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((UpperCAmelCase), (UpperCAmelCase)) = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) UpperCAmelCase = np.asarray(a__ , a__ )[: len(a__ )] plt.scatter( a__ , a__ , label=f"{label_model_name} - {inner_loop_label}: {inner_loop_value}" ) plt.plot(a__ , a__ , '''--''' ) title_str += f" {label_model_name} vs." UpperCAmelCase = title_str[:-4] UpperCAmelCase = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(a__ ) plt.xlabel(a__ ) plt.ylabel(a__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __snake_case ( ) -> Tuple: """simple docstring""" UpperCAmelCase = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = Plot(args=SCREAMING_SNAKE_CASE_ ) plot.plot() if __name__ == "__main__": main()
51
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_longformer''': [ '''LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongformerConfig''', '''LongformerOnnxConfig''', ], '''tokenization_longformer''': ['''LongformerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''LongformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LongformerForMaskedLM''', '''LongformerForMultipleChoice''', '''LongformerForQuestionAnswering''', '''LongformerForSequenceClassification''', '''LongformerForTokenClassification''', '''LongformerModel''', '''LongformerPreTrainedModel''', '''LongformerSelfAttention''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLongformerForMaskedLM''', '''TFLongformerForMultipleChoice''', '''TFLongformerForQuestionAnswering''', '''TFLongformerForSequenceClassification''', '''TFLongformerForTokenClassification''', '''TFLongformerModel''', '''TFLongformerPreTrainedModel''', '''TFLongformerSelfAttention''', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
39
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def __snake_case ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" print('''Loading config file...''' ) def flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]="" , SCREAMING_SNAKE_CASE_ : Dict="." ): UpperCAmelCase = [] for k, v in d.items(): UpperCAmelCase = parent_key + sep + k if parent_key else k if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sep=SCREAMING_SNAKE_CASE_ ).items() ) else: items.append((new_key, v) ) return dict(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = argparse.Namespace() with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as yaml_file: try: UpperCAmelCase = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=yaml.FullLoader ) UpperCAmelCase = flatten_yaml_as_dict(SCREAMING_SNAKE_CASE_ ) for k, v in flat_cfg.items(): setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) ) return config def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase = MobileViTVaConfig() UpperCAmelCase = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase = 384 else: UpperCAmelCase = 256 UpperCAmelCase = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase = 151 UpperCAmelCase = 512 UpperCAmelCase = '''ade20k-id2label.json''' UpperCAmelCase = True elif task_name.startswith('''voc_''' ): UpperCAmelCase = 21 UpperCAmelCase = 512 UpperCAmelCase = '''pascal-voc-id2label.json''' UpperCAmelCase = True # orig_config UpperCAmelCase = load_orig_config_file(SCREAMING_SNAKE_CASE_ ) assert getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase = getattr(SCREAMING_SNAKE_CASE_ , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" UpperCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = val def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str=False ) -> int: """simple docstring""" if base_model: UpperCAmelCase = '''''' else: UpperCAmelCase = '''mobilevitv2.''' UpperCAmelCase = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase = k[8:] else: UpperCAmelCase = k if ".block." in k: UpperCAmelCase = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase = k_new.replace('''conv_1.''' , f"{model_prefix}conv_stem." ) for i in [1, 2]: if f"layer_{i}." in k: UpperCAmelCase = k_new.replace(f"layer_{i}." , f"{model_prefix}encoder.layer.{i-1}.layer." ) if ".exp_1x1." in k: UpperCAmelCase = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f"layer_{i}.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.0." , f"{model_prefix}encoder.layer.{i-1}.downsampling_layer." ) if f"layer_{i}.1.local_rep.0." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.0." , f"{model_prefix}encoder.layer.{i-1}.conv_kxk." ) if f"layer_{i}.1.local_rep.1." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.local_rep.1." , f"{model_prefix}encoder.layer.{i-1}.conv_1x1." ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase = [0, 1] elif i == 4: UpperCAmelCase = [0, 1, 2, 3] elif i == 5: UpperCAmelCase = [0, 1, 2] for j in j_in: if f"layer_{i}.1.global_rep.{j}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j}." , f"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." ) if f"layer_{i}.1.global_rep.{j+1}." in k: UpperCAmelCase = k_new.replace( f"layer_{i}.1.global_rep.{j+1}." , f"{model_prefix}encoder.layer.{i-1}.layernorm." ) if f"layer_{i}.1.conv_proj." in k: UpperCAmelCase = k_new.replace(f"layer_{i}.1.conv_proj." , f"{model_prefix}encoder.layer.{i-1}.conv_projection." ) if "pre_norm_attn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def __snake_case ( SCREAMING_SNAKE_CASE_ : Tuple ) -> int: """simple docstring""" UpperCAmelCase = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(SCREAMING_SNAKE_CASE_ ) for k in keys_to_ignore: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case ( ) -> List[Any]: """simple docstring""" UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase = get_mobilevitva_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load original state_dict UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False else: UpperCAmelCase = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() UpperCAmelCase = False # remove and rename some keys of load the original model UpperCAmelCase = checkpoint remove_unused_keys(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=SCREAMING_SNAKE_CASE_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load modified state_dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase = outputs.logits UpperCAmelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f"Saving model {task_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 __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
51
0