code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse import struct import unittest class snake_case : def __init__( self : List[str] , a_ : bytes )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = data # Initialize hash values SCREAMING_SNAKE_CASE__ : Dict = [ 0x6_a_0_9_e_6_6_7, 0xb_b_6_7_a_e_8_5, 0x3_c_6_e_f_3_7_2, 0xa_5_4_f_f_5_3_a, 0x5_1_0_e_5_2_7_f, 0x9_b_0_5_6_8_8_c, 0x1_f_8_3_d_9_a_b, 0x5_b_e_0_c_d_1_9, ] # Initialize round constants SCREAMING_SNAKE_CASE__ : int = [ 0x4_2_8_a_2_f_9_8, 0x7_1_3_7_4_4_9_1, 0xb_5_c_0_f_b_c_f, 0xe_9_b_5_d_b_a_5, 0x3_9_5_6_c_2_5_b, 0x5_9_f_1_1_1_f_1, 0x9_2_3_f_8_2_a_4, 0xa_b_1_c_5_e_d_5, 0xd_8_0_7_a_a_9_8, 0x1_2_8_3_5_b_0_1, 0x2_4_3_1_8_5_b_e, 0x5_5_0_c_7_d_c_3, 0x7_2_b_e_5_d_7_4, 0x8_0_d_e_b_1_f_e, 0x9_b_d_c_0_6_a_7, 0xc_1_9_b_f_1_7_4, 0xe_4_9_b_6_9_c_1, 0xe_f_b_e_4_7_8_6, 0x0_f_c_1_9_d_c_6, 0x2_4_0_c_a_1_c_c, 0x2_d_e_9_2_c_6_f, 0x4_a_7_4_8_4_a_a, 0x5_c_b_0_a_9_d_c, 0x7_6_f_9_8_8_d_a, 0x9_8_3_e_5_1_5_2, 0xa_8_3_1_c_6_6_d, 0xb_0_0_3_2_7_c_8, 0xb_f_5_9_7_f_c_7, 0xc_6_e_0_0_b_f_3, 0xd_5_a_7_9_1_4_7, 0x0_6_c_a_6_3_5_1, 0x1_4_2_9_2_9_6_7, 0x2_7_b_7_0_a_8_5, 0x2_e_1_b_2_1_3_8, 0x4_d_2_c_6_d_f_c, 0x5_3_3_8_0_d_1_3, 0x6_5_0_a_7_3_5_4, 0x7_6_6_a_0_a_b_b, 0x8_1_c_2_c_9_2_e, 0x9_2_7_2_2_c_8_5, 0xa_2_b_f_e_8_a_1, 0xa_8_1_a_6_6_4_b, 0xc_2_4_b_8_b_7_0, 0xc_7_6_c_5_1_a_3, 0xd_1_9_2_e_8_1_9, 0xd_6_9_9_0_6_2_4, 0xf_4_0_e_3_5_8_5, 0x1_0_6_a_a_0_7_0, 0x1_9_a_4_c_1_1_6, 0x1_e_3_7_6_c_0_8, 0x2_7_4_8_7_7_4_c, 0x3_4_b_0_b_c_b_5, 0x3_9_1_c_0_c_b_3, 0x4_e_d_8_a_a_4_a, 0x5_b_9_c_c_a_4_f, 0x6_8_2_e_6_f_f_3, 0x7_4_8_f_8_2_e_e, 0x7_8_a_5_6_3_6_f, 0x8_4_c_8_7_8_1_4, 0x8_c_c_7_0_2_0_8, 0x9_0_b_e_f_f_f_a, 0xa_4_5_0_6_c_e_b, 0xb_e_f_9_a_3_f_7, 0xc_6_7_1_7_8_f_2, ] SCREAMING_SNAKE_CASE__ : Tuple = self.preprocessing(self.data ) self.final_hash() @staticmethod def __lowercase( a_ : bytes )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = B'\x80' + (B'\x00' * (63 - (len(_snake_case ) + 8) % 64)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = struct.pack('>Q' , (len(_snake_case ) * 8) ) return data + padding + big_endian_integer def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers SCREAMING_SNAKE_CASE__ : Optional[int] = list(struct.unpack('>16L' , _snake_case ) ) # add 48 0-ed integers words += [0] * 48 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array SCREAMING_SNAKE_CASE__ : Any = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) SCREAMING_SNAKE_CASE__ : Dict = ( words[index - 16] + sa + words[index - 7] + sa ) % 0x1_0_0_0_0_0_0_0_0 # Compression SCREAMING_SNAKE_CASE__ : int = self.ror(_snake_case , 6 ) ^ self.ror(_snake_case , 11 ) ^ self.ror(_snake_case , 25 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = (e & f) ^ ((~e & 0xf_f_f_f_f_f_f_f) & g) SCREAMING_SNAKE_CASE__ : int = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0x1_0_0_0_0_0_0_0_0 SCREAMING_SNAKE_CASE__ : List[str] = self.ror(_snake_case , 2 ) ^ self.ror(_snake_case , 13 ) ^ self.ror(_snake_case , 22 ) SCREAMING_SNAKE_CASE__ : Tuple = (a & b) ^ (a & c) ^ (b & c) SCREAMING_SNAKE_CASE__ : Union[str, Any] = (sa + maj) % 0x1_0_0_0_0_0_0_0_0 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = ( g, f, e, ((d + tempa) % 0x1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0x1_0_0_0_0_0_0_0_0), ) SCREAMING_SNAKE_CASE__ : Any = [a, b, c, d, e, f, g, h] # Modify final values SCREAMING_SNAKE_CASE__ : Dict = [ ((element + mutated_hash_values[index]) % 0x1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] SCREAMING_SNAKE_CASE__ : Tuple = ''.join([hex(_snake_case )[2:].zfill(8 ) for value in self.hashes] ) def __lowercase( self : Dict , a_ : int , a_ : int )-> Union[str, Any]: """simple docstring""" return 0xf_f_f_f_f_f_f_f & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): def __lowercase( self : str )-> int: """simple docstring""" import hashlib SCREAMING_SNAKE_CASE__ : str = bytes('Test String' , 'utf-8' ) self.assertEqual(SHAaaa(_snake_case ).hash , hashlib.shaaaa(_snake_case ).hexdigest() ) def _a ( ): '''simple docstring''' import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ : Any = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() SCREAMING_SNAKE_CASE__ : str = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: SCREAMING_SNAKE_CASE__ : Dict = f.read() else: SCREAMING_SNAKE_CASE__ : List[Any] = bytes(__UpperCamelCase , 'utf-8' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class snake_case : def __lowercase( self : List[Any] , a_ : Any )-> str: """simple docstring""" raise NotImplementedError() def __lowercase( self : Dict )-> int: """simple docstring""" raise NotImplementedError() class snake_case ( _lowerCAmelCase ): def __init__( self : Dict , a_ : "AutoTokenizer" , a_ : bool = False , **a_ : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer SCREAMING_SNAKE_CASE__ : Any = skip_prompt SCREAMING_SNAKE_CASE__ : List[Any] = decode_kwargs # variables used in the streaming process SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = True def __lowercase( self : Optional[int] , a_ : List[Any] )-> Optional[Any]: """simple docstring""" if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('TextStreamer only supports batch size 1' ) elif len(value.shape ) > 1: SCREAMING_SNAKE_CASE__ : int = value[0] if self.skip_prompt and self.next_tokens_are_prompt: SCREAMING_SNAKE_CASE__ : Any = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) SCREAMING_SNAKE_CASE__ : Any = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('\n' ): SCREAMING_SNAKE_CASE__ : int = text[self.print_len :] SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : str = 0 # If the last token is a CJK character, we print the characters. elif len(_lowerCAmelCase ) > 0 and self._is_chinese_char(ord(text[-1] ) ): SCREAMING_SNAKE_CASE__ : Optional[Any] = text[self.print_len :] self.print_len += len(_lowerCAmelCase ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: SCREAMING_SNAKE_CASE__ : Tuple = text[self.print_len : text.rfind(' ' ) + 1] self.print_len += len(_lowerCAmelCase ) self.on_finalized_text(_lowerCAmelCase ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" if len(self.token_cache ) > 0: SCREAMING_SNAKE_CASE__ : int = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) SCREAMING_SNAKE_CASE__ : Any = text[self.print_len :] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : List[str] = 0 else: SCREAMING_SNAKE_CASE__ : Optional[Any] = '' SCREAMING_SNAKE_CASE__ : Dict = True self.on_finalized_text(_lowerCAmelCase , stream_end=_lowerCAmelCase ) def __lowercase( self : int , a_ : str , a_ : bool = False )-> str: """simple docstring""" print(_lowerCAmelCase , flush=_lowerCAmelCase , end='' if not stream_end else None ) def __lowercase( self : Tuple , a_ : Tuple )-> int: """simple docstring""" if ( (cp >= 0x4_e_0_0 and cp <= 0x9_f_f_f) or (cp >= 0x3_4_0_0 and cp <= 0x4_d_b_f) # or (cp >= 0x2_0_0_0_0 and cp <= 0x2_a_6_d_f) # or (cp >= 0x2_a_7_0_0 and cp <= 0x2_b_7_3_f) # or (cp >= 0x2_b_7_4_0 and cp <= 0x2_b_8_1_f) # or (cp >= 0x2_b_8_2_0 and cp <= 0x2_c_e_a_f) # or (cp >= 0xf_9_0_0 and cp <= 0xf_a_f_f) or (cp >= 0x2_f_8_0_0 and cp <= 0x2_f_a_1_f) # ): # return True return False class snake_case ( _lowerCAmelCase ): def __init__( self : Optional[int] , a_ : "AutoTokenizer" , a_ : bool = False , a_ : Optional[float] = None , **a_ : List[Any] )-> List[str]: """simple docstring""" super().__init__(_lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = Queue() SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Any = timeout def __lowercase( self : Dict , a_ : str , a_ : bool = False )-> int: """simple docstring""" self.text_queue.put(_lowerCAmelCase , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self : Any )-> Any: """simple docstring""" return self def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) def _a ( lowercase__ : List[str] , lowercase__ : Dict , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = os.path.abspath(snake_case_ ) logger.info(f'''Converting TensorFlow checkpoint from {tf_path}''' ) # Load weights from TF model SCREAMING_SNAKE_CASE__ : List[str] = tf.train.list_variables(snake_case_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") SCREAMING_SNAKE_CASE__ : Tuple = full_name.split('/' ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f'''Skipping non-model layer {full_name}''' ) continue if "optimizer" in full_name: logger.info(f'''Skipping optimization layer {full_name}''' ) continue if name[0] == "model": # ignore initial 'model' SCREAMING_SNAKE_CASE__ : int = name[1:] # figure out how many levels deep the name is SCREAMING_SNAKE_CASE__ : Any = 0 for _name in name: if _name.startswith('layer_with_weights' ): depth += 1 else: break layer_depth.append(snake_case_ ) # read data SCREAMING_SNAKE_CASE__ : List[str] = tf.train.load_variable(snake_case_ , snake_case_ ) names.append('/'.join(snake_case_ ) ) arrays.append(snake_case_ ) logger.info(f'''Read a total of {len(snake_case_ ):,} layers''' ) # Sanity check if len(set(snake_case_ ) ) != 1: raise ValueError(f'''Found layer names with different depths (layer depth {list(set(snake_case_ ) )})''' ) SCREAMING_SNAKE_CASE__ : List[str] = list(set(snake_case_ ) )[0] if layer_depth != 1: raise ValueError( 'The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP' ' heads.' ) # convert layers logger.info('Converting weights...' ) for full_name, array in zip(snake_case_ , snake_case_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = full_name.split('/' ) SCREAMING_SNAKE_CASE__ : Any = model SCREAMING_SNAKE_CASE__ : Any = [] for i, m_name in enumerate(snake_case_ ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith('layer_with_weights' ): SCREAMING_SNAKE_CASE__ : Optional[Any] = int(m_name.split('-' )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(['embeddings', 'LayerNorm'] ) SCREAMING_SNAKE_CASE__ : int = getattr(snake_case_ , 'embeddings' ) SCREAMING_SNAKE_CASE__ : Dict = getattr(snake_case_ , 'LayerNorm' ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(['encoder', 'layer', str(layer_num - 4 )] ) SCREAMING_SNAKE_CASE__ : Any = getattr(snake_case_ , 'encoder' ) SCREAMING_SNAKE_CASE__ : Tuple = getattr(snake_case_ , 'layer' ) SCREAMING_SNAKE_CASE__ : str = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(['pooler', 'dense'] ) SCREAMING_SNAKE_CASE__ : str = getattr(snake_case_ , 'pooler' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(snake_case_ , 'dense' ) elif m_name == "embeddings": trace.append('embeddings' ) SCREAMING_SNAKE_CASE__ : List[str] = getattr(snake_case_ , 'embeddings' ) if layer_num == 0: trace.append('word_embeddings' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'word_embeddings' ) elif layer_num == 1: trace.append('position_embeddings' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'position_embeddings' ) elif layer_num == 2: trace.append('token_type_embeddings' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'token_type_embeddings' ) else: raise ValueError(f'''Unknown embedding layer with name {full_name}''' ) trace.append('weight' ) SCREAMING_SNAKE_CASE__ : Any = getattr(snake_case_ , 'weight' ) elif m_name == "_attention_layer": # self-attention layer trace.extend(['attention', 'self'] ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(snake_case_ , 'attention' ) SCREAMING_SNAKE_CASE__ : List[Any] = getattr(snake_case_ , 'self' ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(['attention', 'output', 'LayerNorm'] ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(snake_case_ , 'attention' ) SCREAMING_SNAKE_CASE__ : Tuple = getattr(snake_case_ , 'output' ) SCREAMING_SNAKE_CASE__ : int = getattr(snake_case_ , 'LayerNorm' ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(['attention', 'output', 'dense'] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'attention' ) SCREAMING_SNAKE_CASE__ : Any = getattr(snake_case_ , 'output' ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(snake_case_ , 'dense' ) elif m_name == "_output_dense": # output dense trace.extend(['output', 'dense'] ) SCREAMING_SNAKE_CASE__ : Any = getattr(snake_case_ , 'output' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(snake_case_ , 'dense' ) elif m_name == "_output_layer_norm": # output dense trace.extend(['output', 'LayerNorm'] ) SCREAMING_SNAKE_CASE__ : str = getattr(snake_case_ , 'output' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(snake_case_ , 'LayerNorm' ) elif m_name == "_key_dense": # attention key trace.append('key' ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(snake_case_ , 'key' ) elif m_name == "_query_dense": # attention query trace.append('query' ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(snake_case_ , 'query' ) elif m_name == "_value_dense": # attention value trace.append('value' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'value' ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(['intermediate', 'dense'] ) SCREAMING_SNAKE_CASE__ : Dict = getattr(snake_case_ , 'intermediate' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(snake_case_ , 'dense' ) elif m_name == "_output_layer_norm": # output layer norm trace.append('output' ) SCREAMING_SNAKE_CASE__ : int = getattr(snake_case_ , 'output' ) # weights & biases elif m_name in ["bias", "beta"]: trace.append('bias' ) SCREAMING_SNAKE_CASE__ : List[str] = getattr(snake_case_ , 'bias' ) elif m_name in ["kernel", "gamma"]: trace.append('weight' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(snake_case_ , 'weight' ) else: logger.warning(f'''Ignored {m_name}''' ) # for certain layers reshape is necessary SCREAMING_SNAKE_CASE__ : List[str] = """.""".join(snake_case_ ) if re.match(r'(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)' , snake_case_ ) or re.match( r'(\S+)\.attention\.output\.dense\.weight' , snake_case_ ): SCREAMING_SNAKE_CASE__ : str = array.reshape(pointer.data.shape ) if "kernel" in full_name: SCREAMING_SNAKE_CASE__ : Tuple = array.transpose() if pointer.shape == array.shape: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.from_numpy(snake_case_ ) else: raise ValueError( f'''Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:''' f''' {array.shape}''' ) logger.info(f'''Successfully set variable {full_name} to PyTorch layer {trace}''' ) return model def _a ( lowercase__ : Union[str, Any] , lowercase__ : Any , lowercase__ : Optional[Any] ): '''simple docstring''' logger.info(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ : Tuple = BertConfig.from_json_file(snake_case_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BertModel(snake_case_ ) # Load weights from checkpoint logger.info(f'''Loading weights from checkpoint {tf_checkpoint_path}...''' ) load_tfa_weights_in_bert(snake_case_ , snake_case_ , snake_case_ ) # Save pytorch-model logger.info(f'''Saving PyTorch model to {pytorch_dump_path}...''' ) torch.save(model.state_dict() , snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() parser.add_argument( "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow 2.x checkpoint path." ) parser.add_argument( "--bert_config_file", type=str, required=True, help="The config json file corresponding to the BERT model. This specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", type=str, required=True, help="Path to the output PyTorch model (must include filename).", ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
import os def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = os.path.dirname(os.path.realpath(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ : int = os.path.join(__UpperCamelCase , 'triangle.txt' ) with open(__UpperCamelCase ) as f: SCREAMING_SNAKE_CASE__ : Dict = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for line in triangle: SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for number in line.strip().split(' ' ): numbers_from_line.append(int(__UpperCamelCase ) ) a.append(__UpperCamelCase ) for i in range(1 , len(__UpperCamelCase ) ): for j in range(len(a[i] ) ): SCREAMING_SNAKE_CASE__ : Optional[Any] = a[i - 1][j] if j != len(a[i - 1] ) else 0 SCREAMING_SNAKE_CASE__ : List[Any] = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(__UpperCamelCase , __UpperCamelCase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
711
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, 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 snake_case ( lowerCAmelCase__ , unittest.TestCase ): lowercase_ = KandinskyVaaControlnetImgaImgPipeline lowercase_ = ["image_embeds", "negative_image_embeds", "image", "hint"] lowercase_ = ["image_embeds", "negative_image_embeds", "image", "hint"] lowercase_ = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowercase_ = False @property def __lowercase( self : List[Any] )-> Dict: """simple docstring""" return 32 @property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return 32 @property def __lowercase( self : Any )-> str: """simple docstring""" return self.time_input_dim @property def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" return self.time_input_dim * 4 @property def __lowercase( self : Optional[Any] )-> int: """simple docstring""" return 100 @property def __lowercase( self : Dict )-> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = { '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__ : Any = UNetaDConditionModel(**_lowerCamelCase ) return model @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" 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 __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = VQModel(**self.dummy_movq_kwargs ) return model def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_unet SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[int] = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } SCREAMING_SNAKE_CASE__ : Optional[Any] = DDIMScheduler(**_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def __lowercase( self : Optional[int] , a_ : List[str] , a_ : Union[str, Any]=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowerCamelCase ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : str = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('RGB' ).resize((256, 256) ) # create hint SCREAMING_SNAKE_CASE__ : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) if str(_lowerCamelCase ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : str = { 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'cpu' SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[int] = self.pipeline_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**self.get_dummy_inputs(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE__ : Any = output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( **self.get_dummy_inputs(_lowerCamelCase ) , return_dict=_lowerCamelCase , )[0] SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Any = np.array( [0.5498_5034, 0.5550_9365, 0.5256_1504, 0.557_0494, 0.559_3818, 0.526_3979, 0.5028_5643, 0.506_9846, 0.5119_6736] ) 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 snake_case ( unittest.TestCase ): def __lowercase( self : int )-> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy' ) SCREAMING_SNAKE_CASE__ : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) SCREAMING_SNAKE_CASE__ : str = init_image.resize((512, 512) ) SCREAMING_SNAKE_CASE__ : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png' ) SCREAMING_SNAKE_CASE__ : Dict = torch.from_numpy(np.array(_lowerCamelCase ) ).float() / 255.0 SCREAMING_SNAKE_CASE__ : Dict = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any = 'A robot, 4k photo' SCREAMING_SNAKE_CASE__ : Any = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : str = pipeline.to(_lowerCamelCase ) pipeline.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = pipe_prior( _lowerCamelCase , image=_lowerCamelCase , strength=0.85 , generator=_lowerCamelCase , negative_prompt='' , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[Any] = pipeline( image=_lowerCamelCase , image_embeds=_lowerCamelCase , negative_image_embeds=_lowerCamelCase , hint=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='np' , ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
import unittest import numpy as np def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : np.ndarray | None = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = np.shape(__snake_case ) SCREAMING_SNAKE_CASE__ : Dict = np.shape(__snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = np.shape(__snake_case ) if shape_a[0] != shape_b[0]: SCREAMING_SNAKE_CASE__ : int = ( "Expected the same number of rows for A and B. " f'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(__snake_case ) if shape_b[1] != shape_c[1]: SCREAMING_SNAKE_CASE__ : Dict = ( "Expected the same number of columns for B and C. " f'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(__snake_case ) SCREAMING_SNAKE_CASE__ : List[Any] = pseudo_inv if a_inv is None: try: SCREAMING_SNAKE_CASE__ : Dict = np.linalg.inv(__snake_case ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE__ : List[str] = np.array([[2, 1], [6, 3]] ) SCREAMING_SNAKE_CASE__ : List[str] = schur_complement(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = np.block([[a, b], [b.T, c]] ) SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.det(a_ ) SCREAMING_SNAKE_CASE__ : Dict = np.linalg.det(a_ ) SCREAMING_SNAKE_CASE__ : Any = np.linalg.det(a_ ) self.assertAlmostEqual(a_ , det_a * det_s ) def __lowercase( self : Any )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE__ : List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(a_ ): schur_complement(a_ , a_ , a_ ) def __lowercase( self : Dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE__ : str = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE__ : Dict = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(a_ ): schur_complement(a_ , a_ , a_ ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
def _a ( lowercase__ : Union[str, Any] , lowercase__ : Dict ): '''simple docstring''' if not isinstance(a__ , a__ ): raise ValueError('iterations must be defined as integers' ) if not isinstance(a__ , a__ ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) SCREAMING_SNAKE_CASE__ : List[Any] = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(a__ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
SCREAMING_SNAKE_CASE__ : int = '''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) def _a ( lowercase__ : np.ndarray , lowercase__ : Union[int, Iterable[int]] , lowercase__ : bool , lowercase__ : int ): '''simple docstring''' def constraint_to_multiple_of(lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Any]=0 , lowercase__ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE__ : Optional[Any] = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE__ : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE__ : Optional[int] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE__ : Tuple = (output_size, output_size) if isinstance(lowercase__ , lowercase__ ) else output_size SCREAMING_SNAKE_CASE__ : Any = get_image_size(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = output_size # determine new height and width SCREAMING_SNAKE_CASE__ : Optional[Any] = output_height / input_height SCREAMING_SNAKE_CASE__ : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE__ : Optional[int] = scale_width else: # fit height SCREAMING_SNAKE_CASE__ : Tuple = scale_height SCREAMING_SNAKE_CASE__ : Optional[int] = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase__ ) SCREAMING_SNAKE_CASE__ : int = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase__ ) return (new_height, new_width) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : Tuple , a_ : Union[str, Any] = True , a_ : int = None , a_ : List[str] = PILImageResampling.BILINEAR , a_ : Any = False , a_ : List[Any] = 1 , a_ : List[str] = True , a_ : int = 1 / 255 , a_ : List[str] = True , a_ : List[str] = None , a_ : int = None , **a_ : Optional[Any] , )-> None: """simple docstring""" super().__init__(**__a ) SCREAMING_SNAKE_CASE__ : Tuple = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(__a ) SCREAMING_SNAKE_CASE__ : int = do_resize SCREAMING_SNAKE_CASE__ : Any = size SCREAMING_SNAKE_CASE__ : Any = keep_aspect_ratio SCREAMING_SNAKE_CASE__ : int = ensure_multiple_of SCREAMING_SNAKE_CASE__ : Dict = resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE__ : List[str] = rescale_factor SCREAMING_SNAKE_CASE__ : int = do_normalize SCREAMING_SNAKE_CASE__ : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE__ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowercase( self : Optional[int] , a_ : Optional[Any] , a_ : Dict , a_ : List[str] = False , a_ : Union[str, Any] = 1 , a_ : Union[str, Any] = PILImageResampling.BICUBIC , a_ : str = None , **a_ : int , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_resize_output_image_size( __a , output_size=(size['height'], size['width']) , keep_aspect_ratio=__a , multiple=__a , ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def __lowercase( self : Dict , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] = None , **a_ : Tuple , )-> Union[str, Any]: """simple docstring""" return rescale(__a , scale=__a , data_format=__a , **__a ) def __lowercase( self : Optional[Any] , a_ : Optional[Any] , a_ : int , a_ : Optional[Any] , a_ : List[str] = None , **a_ : int , )-> np.ndarray: """simple docstring""" return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : List[str] = None , a_ : Union[str, Any] = None , a_ : Dict = None , a_ : int = None , a_ : Union[str, Any] = None , a_ : Optional[Any] = None , a_ : str = None , a_ : Union[str, Any] = None , a_ : Dict = None , a_ : Union[str, Any] = None , a_ : Optional[int] = None , a_ : Optional[Any] = ChannelDimension.FIRST , **a_ : List[Any] , )-> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Optional[int] = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Any = get_size_dict(__a ) SCREAMING_SNAKE_CASE__ : Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE__ : List[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE__ : List[str] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : Optional[Any] = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Any = [to_numpy_array(__a ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : int = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(__a , __a ) for image in images] SCREAMING_SNAKE_CASE__ : Any = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a ) def __lowercase( self : Optional[Any] , a_ : Optional[Any] , a_ : Optional[int] = None )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__a ) != len(__a ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(__a ): SCREAMING_SNAKE_CASE__ : int = target_sizes.numpy() SCREAMING_SNAKE_CASE__ : List[str] = [] for idx in range(len(__a ) ): SCREAMING_SNAKE_CASE__ : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=__a ) SCREAMING_SNAKE_CASE__ : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__a ) else: SCREAMING_SNAKE_CASE__ : Dict = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE__ : Tuple = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = 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_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" 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 __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.getLogger(__name__) require_version("pytorch_lightning>=1.0.4") SCREAMING_SNAKE_CASE__ : List[str] = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, "summarization": AutoModelForSeqaSeqLM, "translation": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization SCREAMING_SNAKE_CASE__ : Optional[int] = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } SCREAMING_SNAKE_CASE__ : str = sorted(arg_to_scheduler.keys()) SCREAMING_SNAKE_CASE__ : Optional[Any] = "{" + ", ".join(arg_to_scheduler_choices) + "}" class snake_case ( pl.LightningModule ): def __init__( self : Union[str, Any] , a_ : argparse.Namespace , a_ : Optional[int]=None , a_ : List[Any]="base" , a_ : int=None , a_ : str=None , a_ : List[Any]=None , **a_ : int , )-> int: """simple docstring""" super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__A ) SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path(self.hparams.output_dir ) SCREAMING_SNAKE_CASE__ : Any = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: SCREAMING_SNAKE_CASE__ : Optional[int] = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'num_labels': num_labels} if num_labels is not None else {}) , cache_dir=__A , **__A , ) else: SCREAMING_SNAKE_CASE__ : str = config SCREAMING_SNAKE_CASE__ : Dict = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(self.hparams , __A , __A ): assert hasattr(self.config , __A ), F'''model config doesn\'t have a `{p}` attribute''' setattr(self.config , __A , getattr(self.hparams , __A ) ) if tokenizer is None: SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__A , ) else: SCREAMING_SNAKE_CASE__ : List[str] = tokenizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = MODEL_MODES[mode] if model is None: SCREAMING_SNAKE_CASE__ : List[Any] = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('.ckpt' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__A , ) else: SCREAMING_SNAKE_CASE__ : Tuple = model def __lowercase( self : int , *a_ : int , **a_ : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_type.from_pretrained(*__A , **__A ) def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = arg_to_scheduler[self.hparams.lr_scheduler] SCREAMING_SNAKE_CASE__ : Optional[int] = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) SCREAMING_SNAKE_CASE__ : Tuple = {'scheduler': scheduler, 'interval': 'step', 'frequency': 1} return scheduler def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model SCREAMING_SNAKE_CASE__ : Optional[Any] = ['bias', 'LayerNorm.weight'] SCREAMING_SNAKE_CASE__ : Optional[int] = [ { 'params': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters 'weight_decay': self.hparams.weight_decay, }, { 'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] if self.hparams.adafactor: SCREAMING_SNAKE_CASE__ : Any = Adafactor( __A , lr=self.hparams.learning_rate , scale_parameter=__A , relative_step=__A ) else: SCREAMING_SNAKE_CASE__ : str = AdamW( __A , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) SCREAMING_SNAKE_CASE__ : int = optimizer SCREAMING_SNAKE_CASE__ : List[str] = self.get_lr_scheduler() return [optimizer], [scheduler] def __lowercase( self : List[Any] , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" return self.validation_step(__A , __A ) def __lowercase( self : int , a_ : Any )-> Optional[int]: """simple docstring""" return self.validation_end(__A ) def __lowercase( self : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores SCREAMING_SNAKE_CASE__ : int = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def __lowercase( self : Union[str, Any] , a_ : List[str] )-> Optional[int]: """simple docstring""" if stage == "test": SCREAMING_SNAKE_CASE__ : int = len(self.test_dataloader().dataset ) else: SCREAMING_SNAKE_CASE__ : Any = self.get_dataloader('train' , self.hparams.train_batch_size , shuffle=__A ) SCREAMING_SNAKE_CASE__ : str = len(self.train_dataloader().dataset ) def __lowercase( self : int , a_ : str , a_ : int , a_ : bool = False )-> Tuple: """simple docstring""" raise NotImplementedError('You must implement this for your task' ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return self.train_loader def __lowercase( self : Dict )-> int: """simple docstring""" return self.get_dataloader('dev' , self.hparams.eval_batch_size , shuffle=__A ) def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" return self.get_dataloader('test' , self.hparams.eval_batch_size , shuffle=__A ) def __lowercase( self : Tuple , a_ : List[Any] )-> List[str]: """simple docstring""" return os.path.join( self.hparams.data_dir , 'cached_{}_{}_{}'.format( __A , list(filter(__A , self.hparams.model_name_or_path.split('/' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def __lowercase( self : Optional[Any] , a_ : Dict[str, Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.output_dir.joinpath('best_tfmr' ) SCREAMING_SNAKE_CASE__ : List[str] = self.step_count self.model.save_pretrained(__A ) self.tokenizer.save_pretrained(__A ) @staticmethod def __lowercase( a_ : Union[str, Any] , a_ : Optional[Any] )-> Dict: """simple docstring""" parser.add_argument( '--model_name_or_path' , default=__A , type=__A , required=__A , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--config_name' , default='' , type=__A , help='Pretrained config name or path if not the same as model_name' ) parser.add_argument( '--tokenizer_name' , default=__A , type=__A , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument( '--cache_dir' , default=str(Path(__A ).parent / 'test_run' / 'cache' ) , type=__A , help='Where do you want to store the pre-trained models downloaded from huggingface.co' , ) parser.add_argument( '--encoder_layerdrop' , type=__A , help='Encoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--decoder_layerdrop' , type=__A , help='Decoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--dropout' , type=__A , help='Dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--attention_dropout' , type=__A , help='Attention dropout probability (Optional). Goes into model.config' , ) parser.add_argument('--learning_rate' , default=5e-5 , type=__A , help='The initial learning rate for Adam.' ) parser.add_argument( '--lr_scheduler' , default='linear' , choices=__A , metavar=__A , type=__A , help='Learning rate scheduler' , ) parser.add_argument('--weight_decay' , default=0.0 , type=__A , help='Weight decay if we apply some.' ) parser.add_argument('--adam_epsilon' , default=1e-8 , type=__A , help='Epsilon for Adam optimizer.' ) parser.add_argument('--warmup_steps' , default=0 , type=__A , help='Linear warmup over warmup_steps.' ) parser.add_argument('--num_workers' , default=4 , type=__A , help='kwarg passed to DataLoader' ) parser.add_argument('--num_train_epochs' , dest='max_epochs' , default=3 , type=__A ) parser.add_argument('--train_batch_size' , default=32 , type=__A ) parser.add_argument('--eval_batch_size' , default=32 , type=__A ) parser.add_argument('--adafactor' , action='store_true' ) class snake_case ( pl.Callback ): def __lowercase( self : Optional[Any] , a_ : str , a_ : List[str] )-> Union[str, Any]: """simple docstring""" if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class snake_case ( pl.Callback ): def __lowercase( self : str , a_ : int , a_ : List[str] )-> List[Any]: """simple docstring""" # print(pl_module.model.rag) for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__A ) class snake_case ( pl.Callback ): def __lowercase( self : int , a_ : Union[str, Any] , a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = trainer.lr_schedulers[0]['scheduler'] SCREAMING_SNAKE_CASE__ : Optional[Any] = {F'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__A ) def __lowercase( self : str , a_ : pl.Trainer , a_ : pl.LightningModule )-> Optional[Any]: """simple docstring""" rank_zero_info('***** Validation results *****' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = trainer.callback_metrics # Log results for key in sorted(__A ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__A , str(metrics[key] ) ) ) def __lowercase( self : Tuple , a_ : pl.Trainer , a_ : pl.LightningModule )-> Optional[Any]: """simple docstring""" rank_zero_info('***** Test results *****' ) SCREAMING_SNAKE_CASE__ : Dict = trainer.callback_metrics # Log and save results to file SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(pl_module.hparams.output_dir , 'test_results.txt' ) with open(__A , 'w' ) as writer: for key in sorted(__A ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__A , str(metrics[key] ) ) ) writer.write('{} = {}\n'.format(__A , str(metrics[key] ) ) ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] ): '''simple docstring''' parser.add_argument( '--output_dir' , default=str(Path(_lowercase ).parent / 'test_run' / 'model_checkpoints' ) , type=_lowercase , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=_lowercase , default='O2' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_tpu_cores' , dest='tpu_cores' , type=_lowercase ) parser.add_argument('--max_grad_norm' , dest='gradient_clip_val' , default=1.0 , type=_lowercase , help='Max gradient norm' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_predict' , action='store_true' , help='Whether to run predictions on the test set.' ) parser.add_argument( '--gradient_accumulation_steps' , dest='accumulate_grad_batches' , type=_lowercase , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--seed' , type=_lowercase , default=42 , help='random seed for initialization' ) parser.add_argument( '--data_dir' , default=str(Path(_lowercase ).parent / 'test_run' / 'dummy-train-data' ) , type=_lowercase , help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.' , ) def _a ( lowercase__ : Optional[Any] , lowercase__ : List[str] , lowercase__ : int=None , lowercase__ : Optional[Any]=True , lowercase__ : Dict=[] , lowercase__ : Any=None , lowercase__ : List[Any]=None , **lowercase__ : int , ): '''simple docstring''' pl.seed_everything(args.seed ) # init model SCREAMING_SNAKE_CASE__ : Dict = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=_lowercase ) # add custom checkpoints if checkpoint_callback is None: SCREAMING_SNAKE_CASE__ : Tuple = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix='checkpoint' , monitor='val_loss' , mode='min' , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(_lowercase ) if logging_callback is None: SCREAMING_SNAKE_CASE__ : Dict = LoggingCallback() SCREAMING_SNAKE_CASE__ : int = {} if args.fpaa: SCREAMING_SNAKE_CASE__ : List[Any] = 16 if args.gpus > 1: SCREAMING_SNAKE_CASE__ : Dict = 'auto' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'ddp' SCREAMING_SNAKE_CASE__ : Optional[int] = args.accumulate_grad_batches SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : List[Any] = 'auto' SCREAMING_SNAKE_CASE__ : List[str] = pl.Trainer.from_argparse_args( _lowercase , weights_summary=_lowercase , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=_lowercase , val_check_interval=1 , num_sanity_val_steps=2 , **_lowercase , ) if args.do_train: trainer.fit(_lowercase ) else: print('RAG modeling tests with new set functions successfuly executed!' ) return trainer
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = { "configuration_graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ "GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. SCREAMING_SNAKE_CASE__ : Dict = abspath(join(dirname(dirname(__file__)), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def _a ( lowercase__ : Any ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE__ : List[str] = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ )
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ : str = {"tokenization_wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
import os from datetime import datetime as dt from github import Github SCREAMING_SNAKE_CASE__ : Optional[int] = [ """good first issue""", """good second issue""", """good difficult issue""", """enhancement""", """new pipeline/model""", """new scheduler""", """wip""", ] def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = Github(os.environ['GITHUB_TOKEN'] ) SCREAMING_SNAKE_CASE__ : Optional[int] = g.get_repo('huggingface/diffusers' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = repo.get_issues(state='open' ) for issue in open_issues: SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(issue.get_comments() , key=lambda lowercase__ : i.created_at , reverse=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = comments[0] if len(_lowerCamelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state='closed' ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state='open' ) issue.remove_from_labels('stale' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) issue.add_to_labels('stale' ) if __name__ == "__main__": main()
700
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( snake_case_ ): lowercase_ = (PNDMScheduler,) lowercase_ = (("""num_inference_steps""", 50),) def __lowercase( self : Optional[Any] , **a_ : List[str] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**a_ ) return config def __lowercase( self : Optional[Any] , a_ : List[Any]=0 , **a_ : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('num_inference_steps' , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.1 * sample SCREAMING_SNAKE_CASE__ : List[str] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : Any = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler_class.from_pretrained(a_ ) new_scheduler.set_timesteps(a_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : str = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step_prk(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Dict = new_scheduler.step_prk(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step_plms(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : List[str] = new_scheduler.step_plms(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowercase( self : str )-> List[str]: """simple docstring""" pass def __lowercase( self : List[Any] , a_ : str=0 , **a_ : int )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : List[str] = kwargs.pop('num_inference_steps' , a_ ) SCREAMING_SNAKE_CASE__ : str = self.dummy_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE__ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : Any = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler_class.from_pretrained(a_ ) # copy over dummy past residuals new_scheduler.set_timesteps(a_ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : List[str] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step_prk(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Dict = new_scheduler.step_prk(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE__ : Tuple = scheduler.step_plms(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : List[str] = new_scheduler.step_plms(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowercase( self : List[str] , **a_ : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = 10 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter scheduler.set_timesteps(a_ ) for i, t in enumerate(scheduler.prk_timesteps ): SCREAMING_SNAKE_CASE__ : Dict = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = scheduler.step_prk(a_ , a_ , a_ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = scheduler.step_plms(a_ , a_ , a_ ).prev_sample return sample def __lowercase( self : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop('num_inference_steps' , a_ ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : str = self.dummy_sample SCREAMING_SNAKE_CASE__ : List[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(a_ , 'set_timesteps' ): scheduler.set_timesteps(a_ ) elif num_inference_steps is not None and not hasattr(a_ , 'set_timesteps' ): SCREAMING_SNAKE_CASE__ : Tuple = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE__ : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE__ : str = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step_prk(a_ , 0 , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step_prk(a_ , 1 , a_ , **a_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step_plms(a_ , 0 , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.step_plms(a_ , 1 , a_ , **a_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=a_ ) def __lowercase( self : str )-> Any: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE__ : str = scheduler_class(**a_ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=a_ , beta_end=a_ ) def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=a_ ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" for t in [1, 5, 10]: self.check_over_forward(time_step=a_ ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 SCREAMING_SNAKE_CASE__ : Tuple = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.1 * sample SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step_prk(a_ , a_ , a_ ).prev_sample def __lowercase( self : int )-> Dict: """simple docstring""" with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler_class(**a_ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.full_loop() SCREAMING_SNAKE_CASE__ : List[str] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 198.1318 ) < 1e-2 assert abs(result_mean.item() - 0.2580 ) < 1e-3 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.full_loop(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 67.3986 ) < 1e-2 assert abs(result_mean.item() - 0.0878 ) < 1e-3 def __lowercase( self : Optional[Any] )-> str: """simple docstring""" # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.full_loop(set_alpha_to_one=a_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 230.0399 ) < 1e-2 assert abs(result_mean.item() - 0.2995 ) < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.full_loop(set_alpha_to_one=a_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 186.9482 ) < 1e-2 assert abs(result_mean.item() - 0.2434 ) < 1e-3
701
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = {"vocab_file": "spiece.model"} SCREAMING_SNAKE_CASE__ : str = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } SCREAMING_SNAKE_CASE__ : Dict = { "AI-Sweden/gpt-sw3-126m": 2048, "AI-Sweden/gpt-sw3-350m": 2048, "AI-Sweden/gpt-sw3-1.6b": 2048, "AI-Sweden/gpt-sw3-6.7b": 2048, "AI-Sweden/gpt-sw3-20b": 2048, } class snake_case ( _UpperCAmelCase ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = ['input_ids', 'attention_mask'] def __init__( self : Union[str, Any] , a_ : Dict , a_ : Dict=False , a_ : Any=False , a_ : List[Any]=False , a_ : int=None , a_ : List[str]=None , a_ : Optional[int]=None , a_ : Union[str, Any]=None , a_ : Optional[Any] = None , **a_ : int , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__ : Dict = kwargs.get('name_or_path' ) if name_or_path is None: logger.warning( 'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,' ' you are testing the model, this can safely be ignored' ) SCREAMING_SNAKE_CASE__ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE__ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE__ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE__ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE__ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE__ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE__ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE__ : Optional[int] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : List[Any] = vocab_file SCREAMING_SNAKE_CASE__ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE__ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE__ : List[str] = re.compile( F'''[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Dict = None return state def __setstate__( self : Optional[int] , a_ : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" return len(self.sp_model ) def __lowercase( self : Union[str, Any] , a_ : Optional[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.non_printing_characters_re.sub('' , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE__ : List[str] = "".join([char if char not in self.whitespaces else ' ' for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE__ : List[Any] = unicodedata.normalize('NFC' , lowercase__ ) return text def __lowercase( self : int , a_ : Dict , **a_ : Union[str, Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> Any: """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowercase( self : int , a_ : List[Any] )-> Optional[Any]: """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowercase( a_ : Dict )-> Any: """simple docstring""" return out_string def __lowercase( self : Optional[Any] , a_ : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase( self : int , a_ : Optional[Any] , a_ : List[str] = None )-> int: """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Any = os.path.join( lowercase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , 'wb' ) as fi: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowercase( self : Dict , a_ : List[str] , a_ : Any = False )-> str: """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE__ : str = torch.tensor(lowercase__ ) return token_ids def __lowercase( self : List[Any] , a_ : str )-> int: """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowercase( self : Any , a_ : List[str] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [F'''User: {text}''' if is_user else F'''Bot: {text}''' for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE__ : List[str] = ( F'''{self.eos_token}{self.bos_token}''' + F'''{self.bos_token}'''.join(lowercase__ ) + F'''{self.bos_token}Bot:''' ) return self.encode(text=lowercase__ )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") SCREAMING_SNAKE_CASE__ : List[str] = logging.getLogger(__name__) @dataclass class snake_case : lowercase_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) lowercase_ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) @dataclass class snake_case : lowercase_ = field(default=UpperCamelCase_ , metadata={'help': 'The input training data file (a text file).'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. If passed, sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': ( 'Whether to pad all samples to the maximum sentence length. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch. More ' 'efficient on GPU but very bad for TPU.' ) } , ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" if self.train_file is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.train_file.split('.' )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.validation_file.split('.' )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class snake_case : lowercase_ = 42 lowercase_ = True lowercase_ = None lowercase_ = None def __call__( self : List[str] , a_ : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'label' if 'label' in features[0].keys() else 'labels' SCREAMING_SNAKE_CASE__ : str = [feature.pop(a_ ) for feature in features] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(features[0]['input_ids'] ) SCREAMING_SNAKE_CASE__ : str = [ [{k: v[i] for k, v in feature.items()} for i in range(a_ )] for feature in features ] SCREAMING_SNAKE_CASE__ : Optional[int] = list(chain(*a_ ) ) SCREAMING_SNAKE_CASE__ : str = self.tokenizer.pad( a_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) # Un-flatten SCREAMING_SNAKE_CASE__ : Optional[int] = {k: v.view(a_ , a_ , -1 ) for k, v in batch.items()} # Add back labels SCREAMING_SNAKE_CASE__ : int = torch.tensor(a_ , dtype=torch.intaa ) return batch def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 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. SCREAMING_SNAKE_CASE__ : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE__ : List[Any] = 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_swag' , 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() SCREAMING_SNAKE_CASE__ : Dict = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE_ ) datasets.utils.logging.set_verbosity(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}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : int = 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 overcome.' ) 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.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} if data_args.train_file is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_args.train_file if data_args.validation_file is not None: SCREAMING_SNAKE_CASE__ : str = data_args.validation_file SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_args.train_file.split('.' )[-1] SCREAMING_SNAKE_CASE__ : List[Any] = load_dataset( SCREAMING_SNAKE_CASE_ , data_files=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. SCREAMING_SNAKE_CASE__ : Union[str, Any] = load_dataset( 'swag' , 'regular' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : List[str] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Tuple = AutoModelForMultipleChoice.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 , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. SCREAMING_SNAKE_CASE__ : Dict = [f'''ending{i}''' for i in range(4 )] SCREAMING_SNAKE_CASE__ : Any = 'sent1' SCREAMING_SNAKE_CASE__ : Dict = 'sent2' if data_args.max_seq_length is None: SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.model_max_length if max_seq_length > 10_24: logger.warning( 'The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value' ' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can' ' override this default with `--block_size xxx`.' ) SCREAMING_SNAKE_CASE__ : Tuple = 10_24 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the''' f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) SCREAMING_SNAKE_CASE__ : List[Any] = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowercase__ : Dict ): SCREAMING_SNAKE_CASE__ : List[str] = [[context] * 4 for context in examples[context_name]] SCREAMING_SNAKE_CASE__ : int = examples[question_header_name] SCREAMING_SNAKE_CASE__ : List[str] = [ [f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(SCREAMING_SNAKE_CASE_ ) ] # Flatten out SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(chain(*SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = list(chain(*SCREAMING_SNAKE_CASE_ ) ) # Tokenize SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) SCREAMING_SNAKE_CASE__ : Dict = raw_datasets['train'] if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : List[str] = min(len(SCREAMING_SNAKE_CASE_ ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(SCREAMING_SNAKE_CASE_ ) ) with training_args.main_process_first(desc='train dataset map pre-processing' ): SCREAMING_SNAKE_CASE__ : int = train_dataset.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) SCREAMING_SNAKE_CASE__ : Any = raw_datasets['validation'] if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = min(len(SCREAMING_SNAKE_CASE_ ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : Dict = eval_dataset.select(range(SCREAMING_SNAKE_CASE_ ) ) with training_args.main_process_first(desc='validation dataset map pre-processing' ): SCREAMING_SNAKE_CASE__ : str = eval_dataset.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator SCREAMING_SNAKE_CASE__ : List[str] = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowercase__ : List[str] ): SCREAMING_SNAKE_CASE__ : Optional[Any] = eval_predictions SCREAMING_SNAKE_CASE__ : Tuple = np.argmax(SCREAMING_SNAKE_CASE_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Optional[int] = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=SCREAMING_SNAKE_CASE_ , data_collator=SCREAMING_SNAKE_CASE_ , compute_metrics=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : str = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : str = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : Optional[Any] = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_ ) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE__ : Tuple = train_result.metrics SCREAMING_SNAKE_CASE__ : List[str] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ) trainer.log_metrics('train' , SCREAMING_SNAKE_CASE_ ) trainer.save_metrics('train' , SCREAMING_SNAKE_CASE_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) SCREAMING_SNAKE_CASE__ : List[str] = trainer.evaluate() SCREAMING_SNAKE_CASE__ : Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = min(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ) trainer.log_metrics('eval' , SCREAMING_SNAKE_CASE_ ) trainer.save_metrics('eval' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Any = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'multiple-choice', 'dataset_tags': 'swag', 'dataset_args': 'regular', 'dataset': 'SWAG', 'language': 'en', } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE_ ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE_ ) def _a ( lowercase__ : List[str] ): '''simple docstring''' main() if __name__ == "__main__": main()
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''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))
636
0
import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py SCREAMING_SNAKE_CASE__ : Optional[Any] = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. SCREAMING_SNAKE_CASE__ : Tuple = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. SCREAMING_SNAKE_CASE__ : Optional[int] = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. SCREAMING_SNAKE_CASE__ : Dict = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) SCREAMING_SNAKE_CASE__ : Tuple = [ ("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"), ("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"), ("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"), ("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"), ("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"), ("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"), ("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"), ("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"), ("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"), ( "zero-shot-object-detection", "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForZeroShotObjectDetection", ), ("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"), ("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"), ("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"), ("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"), ( "table-question-answering", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForTableQuestionAnswering", ), ("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"), ("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"), ( "next-sentence-prediction", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", "AutoModelForNextSentencePrediction", ), ( "audio-frame-classification", "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioFrameClassification", ), ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), ( "document-question-answering", "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForDocumentQuestionAnswering", ), ( "visual-question-answering", "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForVisualQuestionAnswering", ), ("image-to-text", "MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"), ( "zero-shot-image-classification", "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForZeroShotImageClassification", ), ("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"), ("video-classification", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForVideoClassification"), ("mask-generation", "MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "AutoModelForMaskGeneration"), ] def _a ( lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , __lowercase ) return [m.group(0 ) for m in matches] def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE__ : Dict = { config.replace('Config' , '' ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. SCREAMING_SNAKE_CASE__ : List[Any] = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple = collections.defaultdict(__lowercase ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(__lowercase ): SCREAMING_SNAKE_CASE__ : Tuple = None if _re_tf_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE__ : List[str] = tf_models SCREAMING_SNAKE_CASE__ : Any = _re_tf_models.match(__lowercase ).groups()[0] elif _re_flax_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = flax_models SCREAMING_SNAKE_CASE__ : int = _re_flax_models.match(__lowercase ).groups()[0] elif _re_pt_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = pt_models SCREAMING_SNAKE_CASE__ : Tuple = _re_pt_models.match(__lowercase ).groups()[0] if lookup_dict is not None: while len(__lowercase ) > 0: if attr_name in model_prefix_to_model_type: SCREAMING_SNAKE_CASE__ : Any = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE__ : Dict = ''.join(camel_case_split(__lowercase )[:-1] ) SCREAMING_SNAKE_CASE__ : Any = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) SCREAMING_SNAKE_CASE__ : Tuple = list(__lowercase ) all_models.sort() SCREAMING_SNAKE_CASE__ : str = {'model_type': all_models} SCREAMING_SNAKE_CASE__ : Optional[int] = [pt_models[t] for t in all_models] SCREAMING_SNAKE_CASE__ : str = [tf_models[t] for t in all_models] SCREAMING_SNAKE_CASE__ : List[Any] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure SCREAMING_SNAKE_CASE__ : List[Any] = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE__ : List[Any] = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: SCREAMING_SNAKE_CASE__ : Optional[int] = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE__ : List[str] = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. SCREAMING_SNAKE_CASE__ : Dict = 'AutoTokenizer' SCREAMING_SNAKE_CASE__ : List[Any] = [processors[t] for t in all_models] return pd.DataFrame(__lowercase ) def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: SCREAMING_SNAKE_CASE__ : Any = [model_mapping, f'''TF_{model_mapping}''', f'''FLAX_{model_mapping}'''] SCREAMING_SNAKE_CASE__ : Optional[Any] = [auto_class, f'''TF_{auto_class}''', f'''Flax_{auto_class}'''] # Loop through all three frameworks for module, cls, mapping in zip(__lowercase , __lowercase , __lowercase ): # The type of pipeline may not exist in this framework if not hasattr(__lowercase , __lowercase ): continue # First extract all model_names SCREAMING_SNAKE_CASE__ : Optional[int] = [] for name in getattr(__lowercase , __lowercase ).values(): if isinstance(__lowercase , __lowercase ): model_names.append(__lowercase ) else: model_names.extend(list(__lowercase ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def _a ( lowercase__ : Optional[int] , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = get_frameworks_table() SCREAMING_SNAKE_CASE__ : Any = Dataset.from_pandas(__lowercase ) SCREAMING_SNAKE_CASE__ : Any = hf_hub_download( 'huggingface/transformers-metadata' , 'pipeline_tags.json' , repo_type='dataset' , token=__lowercase ) SCREAMING_SNAKE_CASE__ : Dict = Dataset.from_json(__lowercase ) SCREAMING_SNAKE_CASE__ : Any = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(__lowercase ) ) } SCREAMING_SNAKE_CASE__ : str = update_pipeline_and_auto_class_table(__lowercase ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. SCREAMING_SNAKE_CASE__ : Optional[int] = sorted(table.keys() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pd.DataFrame( { 'model_class': model_classes, 'pipeline_tag': [table[m][0] for m in model_classes], 'auto_class': [table[m][1] for m in model_classes], } ) SCREAMING_SNAKE_CASE__ : Any = Dataset.from_pandas(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(__lowercase , 'frameworks.json' ) ) tags_dataset.to_json(os.path.join(__lowercase , 'pipeline_tags.json' ) ) if commit_sha is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = ( f'''Update with commit {commit_sha}\n\nSee: ''' f'''https://github.com/huggingface/transformers/commit/{commit_sha}''' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = 'Update' upload_folder( repo_id='huggingface/transformers-metadata' , folder_path=__lowercase , repo_type='dataset' , token=__lowercase , commit_message=__lowercase , ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} SCREAMING_SNAKE_CASE__ : List[Any] = transformers_module.pipelines.SUPPORTED_TASKS SCREAMING_SNAKE_CASE__ : Optional[int] = [] for key in pipeline_tasks: if key not in in_table: SCREAMING_SNAKE_CASE__ : str = pipeline_tasks[key]['pt'] if isinstance(__lowercase , (list, tuple) ): SCREAMING_SNAKE_CASE__ : Dict = model[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model.__name__ if model not in in_table.values(): missing.append(__lowercase ) if len(__lowercase ) > 0: SCREAMING_SNAKE_CASE__ : Any = ', '.join(__lowercase ) raise ValueError( 'The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside ' f'''`utils/update_metadata.py`: {msg}. Please add them!''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--token", type=str, help="The token to use to push to the transformers-metadata dataset.") parser.add_argument("--commit_sha", type=str, help="The sha of the commit going with this update.") parser.add_argument("--check-only", action="store_true", help="Activate to just check all pipelines are present.") SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ : Tuple = 16 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 32 def _a ( lowercase__ : Optional[Any] , lowercase__ : Tuple = 16 ): '''simple docstring''' __A : int = AutoTokenizer.from_pretrained('bert-base-cased' ) __A : Dict = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowercase__ : Dict ): # max_length=None => use the model max length (it's actually the default) __A : Union[str, Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__snake_case , max_length=__snake_case ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A : Dict = datasets.map( __snake_case , batched=__snake_case , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __A : str = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowercase__ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. __A : str = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A : Optional[Any] = 16 elif accelerator.mixed_precision != "no": __A : Dict = 8 else: __A : Optional[Any] = None return tokenizer.pad( __snake_case , padding='longest' , max_length=__snake_case , pad_to_multiple_of=__snake_case , return_tensors='pt' , ) # Instantiate dataloaders. __A : Optional[Any] = DataLoader( tokenized_datasets['train'] , shuffle=__snake_case , collate_fn=__snake_case , batch_size=__snake_case ) __A : str = DataLoader( tokenized_datasets['validation'] , shuffle=__snake_case , collate_fn=__snake_case , batch_size=__snake_case ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ : Optional[Any] = mocked_dataloaders # noqa: F811 def _a ( lowercase__ : List[str] , lowercase__ : Any ): '''simple docstring''' if os.environ.get('TESTING_MOCKED_DATALOADERS' , __snake_case ) == "1": __A : Union[str, Any] = 2 # Initialize accelerator __A : Optional[int] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A : Optional[Any] = config['lr'] __A : str = int(config['num_epochs'] ) __A : Dict = int(config['seed'] ) __A : Union[str, Any] = int(config['batch_size'] ) __A : Union[str, Any] = evaluate.load('glue' , 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__snake_case ) def inner_training_loop(lowercase__ : Optional[int] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__snake_case ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A : Optional[int] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__snake_case ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __A : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer __A : Optional[Any] = AdamW(params=model.parameters() , lr=__snake_case ) __A , __A : Optional[Any] = get_dataloaders(__snake_case , __snake_case ) # Instantiate scheduler __A : int = get_linear_schedule_with_warmup( optimizer=__snake_case , num_warmup_steps=1_00 , num_training_steps=(len(__snake_case ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A , __A , __A , __A , __A : Union[str, Any] = accelerator.prepare( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) # Now we train the model for epoch in range(__snake_case ): model.train() for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __A : Tuple = model(**__snake_case ) __A : int = outputs.loss accelerator.backward(__snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __A : Optional[int] = model(**__snake_case ) __A : Dict = outputs.logits.argmax(dim=-1 ) __A , __A : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__snake_case , references=__snake_case , ) __A : Any = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , __snake_case ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def _a ( ): '''simple docstring''' __A : List[Any] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__snake_case , default=__snake_case , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) __A : Any = parser.parse_args() __A : int = {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(__snake_case , __snake_case ) if __name__ == "__main__": main()
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.getLogger(__name__) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=lowerCAmelCase__ , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=lowerCAmelCase__ , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=lowerCAmelCase__ , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=lowerCAmelCase__ , default='data/dump' , help='The dump file prefix.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() logger.info(f'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map['cls_token'] # `[CLS]` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map['sep_token'] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : Tuple = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.special_tokens_map['cls_token'] # `<s>` SCREAMING_SNAKE_CASE__ : Any = tokenizer.special_tokens_map['sep_token'] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : Tuple = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.special_tokens_map['bos_token'] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.special_tokens_map['eos_token'] # `<|endoftext|>` logger.info(f'''Loading text from {args.file_path}''' ) with open(args.file_path , 'r' , encoding='utf8' ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info('Start encoding' ) logger.info(f'''{len(lowerCAmelCase__ )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_00_00 SCREAMING_SNAKE_CASE__ : Optional[int] = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) rslt.append(lowerCAmelCase__ ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : List[Any] = time.time() logger.info(f'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = time.time() logger.info('Finished binarization' ) logger.info(f'''{len(lowerCAmelCase__ )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = f'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Optional[int] = [np.uintaa(lowerCAmelCase__ ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Tuple = [np.intaa(lowerCAmelCase__ ) for d in rslt] random.shuffle(rslt_ ) logger.info(f'''Dump to {dp_file}''' ) with open(lowerCAmelCase__ , 'wb' ) as handle: pickle.dump(rslt_ , lowerCAmelCase__ , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( 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 , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ : Dict = 16 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 32 def _a ( lowercase__ : int , lowercase__ : Any = 16 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE__ : List[str] = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowercase__ : Any ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : str = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : int = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowercase__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : List[str] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : Dict = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Optional[int] = 8 else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None return tokenizer.pad( lowerCAmelCase_ , padding='longest' , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : Optional[int] = DataLoader( tokenized_datasets['train'] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : str = DataLoader( tokenized_datasets['validation'] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ : List[Any] = mocked_dataloaders # noqa: F811 def _a ( lowercase__ : Union[str, Any] , lowercase__ : int ): '''simple docstring''' if os.environ.get('TESTING_MOCKED_DATALOADERS' , lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE__ : List[str] = 2 # Initialize accelerator SCREAMING_SNAKE_CASE__ : List[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Dict = config["lr"] SCREAMING_SNAKE_CASE__ : Dict = int(config['num_epochs'] ) SCREAMING_SNAKE_CASE__ : int = int(config['seed'] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config['batch_size'] ) SCREAMING_SNAKE_CASE__ : List[str] = evaluate.load('glue' , 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowercase__ : List[Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : List[Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Dict = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Dict = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : str = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=1_00 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ : List[Any] = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE__ : Tuple = model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : str = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] = model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : str = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=lowerCAmelCase_ , default=lowerCAmelCase_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
import torch from diffusers import StableDiffusionPipeline SCREAMING_SNAKE_CASE__ : int = "path-to-your-trained-model" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("cuda") SCREAMING_SNAKE_CASE__ : Any = "A photo of sks dog in a bucket" SCREAMING_SNAKE_CASE__ : str = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0] image.save("dog-bucket.png")
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) class snake_case ( lowerCAmelCase__ ): lowercase_ = ["pixel_values"] def __init__( self : int , a_ : Any = True , a_ : Dict = 32 , a_ : str=PILImageResampling.BILINEAR , a_ : Optional[Any] = True , **a_ : int , )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = do_resize SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE__ : Tuple = size_divisor SCREAMING_SNAKE_CASE__ : Optional[int] = resample super().__init__(**_SCREAMING_SNAKE_CASE ) def __lowercase( self : Optional[int] , a_ : Optional[int] , a_ : List[str] , a_ : List[Any] , a_ : str = None , **a_ : int )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = get_image_size(_SCREAMING_SNAKE_CASE ) # Rounds the height and width down to the closest multiple of size_divisor SCREAMING_SNAKE_CASE__ : Any = height // size_divisor * size_divisor SCREAMING_SNAKE_CASE__ : str = width // size_divisor * size_divisor SCREAMING_SNAKE_CASE__ : str = resize(_SCREAMING_SNAKE_CASE , (new_h, new_w) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return image def __lowercase( self : Dict , a_ : Optional[Any] , a_ : List[str] , a_ : str = None , **a_ : int )-> np.ndarray: """simple docstring""" return rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowercase( self : Optional[Any] , a_ : List[str] , a_ : str = None , a_ : Optional[Any] = None , a_ : Any=None , a_ : List[Any] = None , a_ : Dict = None , a_ : Union[str, Any] = ChannelDimension.FIRST , **a_ : Tuple , )-> BatchFeature: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Optional[int] = size_divisor if size_divisor is not None else self.size_divisor SCREAMING_SNAKE_CASE__ : List[str] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('size_divisor is required for resizing' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError('Invalid image(s)' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : int = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for img in images] if do_resize: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.resize(_SCREAMING_SNAKE_CASE , size_divisor=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.rescale(_SCREAMING_SNAKE_CASE , scale=1 / 255 ) for image in images] SCREAMING_SNAKE_CASE__ : List[Any] = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = {'pixel_values': images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument SCREAMING_SNAKE_CASE__ : Union[str, Any] = { '/attention/': '/0/SelfAttention/', '/self_attention/': '/0/SelfAttention/', '/encoder_decoder_attention/': '/1/EncDecAttention/', 'value': 'v', 'query': 'q', 'key': 'k', 'out': 'o', 'pre_self_attention_layer_norm': '0/layer_norm', 'pre_cross_attention_layer_norm': '1/layer_norm', 'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong 'token_embedder': 'shared', 'encoder_norm': 'final_layer_norm', 'decoder_norm': 'final_layer_norm', 'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight', 'router/router_weights/w/': 'router/classifier/', 'roer/roer_weights/w/': 'router/classifier/', 'logits_dense': 'lm_head', } def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = list(s_dict.keys() ) for key in keys: SCREAMING_SNAKE_CASE__ : List[Any] = r'.*/layers_(\d+)' SCREAMING_SNAKE_CASE__ : Optional[Any] = key if re.match(A_ , A_ ): SCREAMING_SNAKE_CASE__ : List[Any] = re.sub(r'layers_(\d+)' , r'block/\1/layer' , A_ ) SCREAMING_SNAKE_CASE__ : Tuple = r'(encoder|decoder)\/' if re.match(A_ , A_ ): SCREAMING_SNAKE_CASE__ : Dict = re.match(A_ , A_ ).groups() if groups[0] == "encoder": SCREAMING_SNAKE_CASE__ : List[str] = re.sub(r'/mlp/' , r'/1/mlp/' , A_ ) SCREAMING_SNAKE_CASE__ : int = re.sub(r'/pre_mlp_layer_norm/' , r'/1/layer_norm/' , A_ ) elif groups[0] == "decoder": SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.sub(r'/mlp/' , r'/2/mlp/' , A_ ) SCREAMING_SNAKE_CASE__ : int = re.sub(r'/pre_mlp_layer_norm/' , r'/2/layer_norm/' , A_ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: SCREAMING_SNAKE_CASE__ : Tuple = new_key.replace(A_ , A_ ) print(f'''{key} -> {new_key}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = s_dict.pop(A_ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE__ : Optional[int] = s_dict[ 'encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE__ : Dict = s_dict[ 'decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: SCREAMING_SNAKE_CASE__ : int = s_dict[key].shape[0] SCREAMING_SNAKE_CASE__ : str = s_dict[key] for idx in range(A_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = expert_weihts[idx] print(f'''{key} -> {key.replace('expert/' , 'nested fstring' )}''' ) s_dict.pop(A_ ) return s_dict SCREAMING_SNAKE_CASE__ : Dict = { 'NUM_ENCODER_LAYERS': 'num_layers', 'NUM_DECODER_LAYERS': 'num_decoder_layers', 'NUM_HEADS': 'num_heads', 'HEAD_DIM': 'd_kv', 'EMBED_DIM': 'd_model', 'MLP_DIM': 'd_ff', 'NUM_SELECTED_EXPERTS': 'num_selected_experts', 'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers', 'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers', 'dense.MlpBlock.activations': 'feed_forward_proj', } def _a ( lowercase__ : List[Any] , lowercase__ : str ): '''simple docstring''' import regex as re with open(A_ , 'r' ) as f: SCREAMING_SNAKE_CASE__ : str = f.read() SCREAMING_SNAKE_CASE__ : Dict = re.findall(r'(.*) = ([0-9.]*)' , A_ ) SCREAMING_SNAKE_CASE__ : List[Any] = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": SCREAMING_SNAKE_CASE__ : Optional[int] = float(A_ ) if '.' in value else int(A_ ) SCREAMING_SNAKE_CASE__ : int = re.findall(r'(.*activations) = \(\'(.*)\',\)' , A_ )[0] SCREAMING_SNAKE_CASE__ : int = str(activation[1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_experts SCREAMING_SNAKE_CASE__ : Any = SwitchTransformersConfig(**A_ ) return config def _a ( lowercase__ : Optional[int] , lowercase__ : Union[str, Any] , lowercase__ : List[str]=None , lowercase__ : int="./" , lowercase__ : List[Any]=8 ): '''simple docstring''' print(f'''Loading flax weights from : {flax_checkpoint_path}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = checkpoints.load_tax_checkpoint(A_ ) if gin_file is not None: SCREAMING_SNAKE_CASE__ : int = convert_gin_to_config(A_ , A_ ) else: SCREAMING_SNAKE_CASE__ : Tuple = SwitchTransformersConfig.from_pretrained(A_ ) SCREAMING_SNAKE_CASE__ : List[Any] = SwitchTransformersForConditionalGeneration(A_ ) SCREAMING_SNAKE_CASE__ : List[Any] = flax_params['target'] SCREAMING_SNAKE_CASE__ : List[str] = flatten_dict(A_ , sep='/' ) SCREAMING_SNAKE_CASE__ : int = rename_keys(A_ ) SCREAMING_SNAKE_CASE__ : int = unflatten_dict(A_ , sep='/' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(A_ , A_ ) print(f'''Save PyTorch model to {pytorch_dump_path}''' ) pt_model.save_pretrained(A_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the" " model architecture. If not provided, a `gin_file` has to be provided." ), ) parser.add_argument( "--gin_file", default=None, type=str, required=False, help="Path to the gin config file. If not provided, a `config_file` has to be passed ", ) parser.add_argument( "--config_name", default=None, type=str, required=False, help="Config name of SwitchTransformers model." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output pytorch model." ) parser.add_argument("--num_experts", default=8, type=int, required=False, help="Number of experts") SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Optional[int] = { '''bart''': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''bert''': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-base-cased-finetuned-mrpc''': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''dpr''': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''gpt2''': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlnet''': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm''': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm-roberta''': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''transfo-xl''': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''openai-gpt''': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''roberta''': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''layoutlm''': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''roberta-large-mnli''': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''camembert''': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''flaubert''': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert''': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert-base-distilled-squad''': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert''': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert-visual-feature-encoder''': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''ctrl''': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''albert''': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''t5''': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''electra''': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''wav2vec2''': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def _a ( lowercase__ : List[str] , lowercase__ : Optional[int] , lowercase__ : Union[str, Any] , lowercase__ : Optional[int] , lowercase__ : List[str]=False , lowercase__ : List[Any]=True ): '''simple docstring''' if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) SCREAMING_SNAKE_CASE__ : List[str] = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: SCREAMING_SNAKE_CASE__ : List[str] = cached_file(lowercase__ , lowercase__ , force_download=not use_cached_models ) SCREAMING_SNAKE_CASE__ : Tuple = config_class.from_json_file(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Optional[Any] = True print(f'''Building TensorFlow model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ : str = model_class(lowercase__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): SCREAMING_SNAKE_CASE__ : Dict = cached_file( lowercase__ , lowercase__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: SCREAMING_SNAKE_CASE__ : Optional[int] = load_pytorch_checkpoint_in_tfa_model(lowercase__ , lowercase__ ) if compare_with_pt_model: SCREAMING_SNAKE_CASE__ : Tuple = tf_model(tf_model.dummy_inputs , training=lowercase__ ) # build the network SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(lowercase__ , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Optional[int] = pt_model_class.from_pretrained( pretrained_model_name_or_path=lowercase__ , config=lowercase__ , state_dict=lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = pt_model(**pt_model.dummy_inputs ) SCREAMING_SNAKE_CASE__ : int = pto[0].numpy() SCREAMING_SNAKE_CASE__ : List[Any] = tfo[0].numpy() SCREAMING_SNAKE_CASE__ : Optional[int] = np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2E-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(lowercase__ , save_format='h5' ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Dict , lowercase__ : Union[str, Any]=None , lowercase__ : List[str]=None , lowercase__ : Any=False , lowercase__ : Union[str, Any]=False , lowercase__ : Union[str, Any]=False , lowercase__ : int=False , ): '''simple docstring''' if args_model_type is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(MODEL_CLASSES.keys() ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [args_model_type] for j, model_type in enumerate(lowercase__ , start=1 ): print('=' * 1_00 ) print(f''' Converting model type {j}/{len(lowercase__ )}: {model_type}''' ) print('=' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) SCREAMING_SNAKE_CASE__ : Tuple = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: SCREAMING_SNAKE_CASE__ : List[str] = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(lowercase__ , lowercase__ ) , start=1 ): print('-' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue SCREAMING_SNAKE_CASE__ : int = model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(lowercase__ )}: {model_shortcut_name} - model_type {model_type}''' ) print('-' * 1_00 ) if config_shortcut_name in aws_config_map: SCREAMING_SNAKE_CASE__ : List[Any] = cached_file(lowercase__ , lowercase__ , force_download=not use_cached_models ) else: SCREAMING_SNAKE_CASE__ : Any = config_shortcut_name if model_shortcut_name in aws_model_maps: SCREAMING_SNAKE_CASE__ : Tuple = cached_file(lowercase__ , lowercase__ , force_download=not use_cached_models ) else: SCREAMING_SNAKE_CASE__ : List[str] = model_shortcut_name if os.path.isfile(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = 'converted_model' convert_pt_checkpoint_to_tf( model_type=lowercase__ , pytorch_checkpoint_path=lowercase__ , config_file=lowercase__ , tf_dump_path=os.path.join(lowercase__ , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=lowercase__ , ) if remove_cached_files: os.remove(lowercase__ ) os.remove(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
711
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import requests def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'Content-Type': 'application/json'} SCREAMING_SNAKE_CASE__ : int = requests.post(__snake_case , json={'text': message_body} , headers=__snake_case ) if response.status_code != 2_00: SCREAMING_SNAKE_CASE__ : str = ( 'Request to slack returned an error ' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(__snake_case ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( lowercase_ , unittest.TestCase ): lowercase_ = CLIPTokenizer lowercase_ = CLIPTokenizerFast lowercase_ = True lowercase_ = {} lowercase_ = False def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # fmt: off SCREAMING_SNAKE_CASE__ : Any = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on SCREAMING_SNAKE_CASE__ : Tuple = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) SCREAMING_SNAKE_CASE__ : int = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>"""] SCREAMING_SNAKE_CASE__ : str = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ : 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(lowerCamelCase_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(lowerCamelCase_ ) ) def __lowercase( self : Union[str, Any] , **a_ : Any )-> Union[str, Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase_ ) def __lowercase( self : Dict , **a_ : Any )-> List[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCamelCase_ ) def __lowercase( self : Dict , a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" return input_text, output_text def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : List[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Dict = ["""lo""", """w""", """er</w>""", """n""", """e""", """w""", """er</w>"""] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : str = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Optional[int] = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ ) @require_ftfy def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = """A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d.""" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_s.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_r.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways SCREAMING_SNAKE_CASE__ : int = """xa\u0303y""" + """ """ + """x\xe3y""" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_s.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_r.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # Test that the tokenization is identical on unicode of space type SCREAMING_SNAKE_CASE__ : str = [ """\u0009""", # (horizontal tab, '\t') """\u000B""", # (vertical tab) """\u000C""", # (form feed) """\u0020""", # (space, ' ') """\u200E""", # (left-to-right mark):w """\u200F""", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: SCREAMING_SNAKE_CASE__ : int = tokenizer_s.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_r.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # Test that the tokenization is identical on unicode of line break type SCREAMING_SNAKE_CASE__ : Dict = [ """\u000A""", # (line feed, '\n') """\r\n""", # (carriage return and line feed, '\r\n') """\u000D""", # (carriage return, '\r') """\r""", # (carriage return, '\r') """\u000D""", # (carriage return, '\r') """\u2028""", # (line separator) """\u2029""", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: SCREAMING_SNAKE_CASE__ : str = tokenizer_s.tokenize(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer_r.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : List[Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE__ : Dict = F'''{text_of_1_token} {text_of_1_token}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ , use_fast=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE__ : Any = tokenizer_r(lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase_ ) + 1, len(lowerCamelCase_ ) + 1 + len(lowerCamelCase_ )) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = F''' {text}''' SCREAMING_SNAKE_CASE__ : Tuple = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ , use_fast=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_r(lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowerCamelCase_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowerCamelCase_ ) + 1, 1 + len(lowerCamelCase_ ) + 1 + len(lowerCamelCase_ )) , ) def __lowercase( self : int )-> Dict: """simple docstring""" with self.assertRaises(lowerCamelCase_ ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def __lowercase( self : int )-> Any: """simple docstring""" super().test_tokenization_python_rust_equals() def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" pass
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
SCREAMING_SNAKE_CASE__ : int = 8.31_4462 # Unit - J mol-1 K-1 def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError('Invalid inputs. Enter positive value.' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError('Invalid inputs. Enter positive value.' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json", "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json", } class snake_case ( _UpperCamelCase ): lowercase_ = 'falcon' lowercase_ = ['past_key_values'] def __init__( self : List[Any] , a_ : int=6_5024 , a_ : int=4544 , a_ : List[Any]=32 , a_ : str=71 , a_ : Optional[Any]=1e-5 , a_ : List[Any]=0.02 , a_ : Any=True , a_ : Optional[int]=0.0 , a_ : str=0.0 , a_ : Optional[int]=None , a_ : Optional[int]=False , a_ : int=False , a_ : Union[str, Any]=True , a_ : List[Any]=True , a_ : str=False , a_ : Union[str, Any]=11 , a_ : Optional[Any]=11 , **a_ : Union[str, Any] , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = vocab_size # Backward compatibility with n_embed kwarg SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop('n_embed' , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = hidden_size if n_embed is None else n_embed SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = use_cache SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : Dict = bos_token_id SCREAMING_SNAKE_CASE__ : List[str] = eos_token_id SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads if num_kv_heads is None else num_kv_heads SCREAMING_SNAKE_CASE__ : List[Any] = alibi SCREAMING_SNAKE_CASE__ : List[str] = new_decoder_architecture SCREAMING_SNAKE_CASE__ : Tuple = multi_query # Ignored when new_decoder_architecture is True SCREAMING_SNAKE_CASE__ : Optional[int] = parallel_attn SCREAMING_SNAKE_CASE__ : str = bias super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.hidden_size // self.num_attention_heads @property def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" return not self.alibi
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
def _a ( lowercase__ : Optional[Any] , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = len(a__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): SCREAMING_SNAKE_CASE__ : Any = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): SCREAMING_SNAKE_CASE__ : Optional[int] = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: SCREAMING_SNAKE_CASE__ : Union[str, Any] = subset[i - 1][j] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE__ : Optional[Any] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' # Copyright 2022 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 import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file SCREAMING_SNAKE_CASE__ : List[str] = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def _a ( lowercase__ : Tuple=None ): '''simple docstring''' if subparsers is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = subparsers.add_parser('tpu-config' , description=_description ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments SCREAMING_SNAKE_CASE__ : Tuple = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=snake_case__ , default=snake_case__ , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=snake_case__ , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=snake_case__ , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) SCREAMING_SNAKE_CASE__ : List[str] = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=snake_case__ , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=snake_case__ ) return parser def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(snake_case__ ): SCREAMING_SNAKE_CASE__ : int = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: SCREAMING_SNAKE_CASE__ : str = defaults.command_file if not args.command and defaults.commands is not None: SCREAMING_SNAKE_CASE__ : Tuple = defaults.commands if not args.tpu_name: SCREAMING_SNAKE_CASE__ : List[Any] = defaults.tpu_name if not args.tpu_zone: SCREAMING_SNAKE_CASE__ : int = defaults.tpu_zone if args.accelerate_version == "dev": SCREAMING_SNAKE_CASE__ : Tuple = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": SCREAMING_SNAKE_CASE__ : str = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , snake_case__ ): SCREAMING_SNAKE_CASE__ : List[Any] = f'''accelerate=={args.accelerate_version}''' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: SCREAMING_SNAKE_CASE__ : int = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , snake_case__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate SCREAMING_SNAKE_CASE__ : Dict = ['cd /usr/share'] if args.install_accelerate: new_cmd += [f'''pip install {args.accelerate_version}'''] new_cmd += args.command SCREAMING_SNAKE_CASE__ : Tuple = '; '.join(snake_case__ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess SCREAMING_SNAKE_CASE__ : List[Any] = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f'''Running {' '.join(snake_case__ )}''' ) return subprocess.run(snake_case__ ) print('Successfully setup pod.' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = tpu_command_parser() SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() tpu_command_launcher(snake_case__ )
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = 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_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" 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 __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = LongformerTokenizer lowercase_ = True lowercase_ = LongformerTokenizerFast lowercase_ = True def __lowercase( self : str )-> List[Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : int = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE__ : str = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE__ : List[Any] = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(UpperCAmelCase__ ) ) def __lowercase( self : Dict , **a_ : Optional[int] )-> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def __lowercase( self : Any , **a_ : Tuple )-> Any: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def __lowercase( self : Any , a_ : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '''lower newer''' SCREAMING_SNAKE_CASE__ : Optional[int] = '''lower newer''' return input_text, output_text def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Tuple = '''lower newer''' SCREAMING_SNAKE_CASE__ : List[Any] = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.tokenize(UpperCAmelCase__ ) # , add_prefix_space=True) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() self.assertListEqual(tokenizer.encode('Hello world!' , add_special_tokens=UpperCAmelCase__ ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('Hello world! cécé herlolip 418' , add_special_tokens=UpperCAmelCase__ ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.tokenizer_class.from_pretrained('allenai/longformer-base-4096' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode('sequence builders' , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode('multi-sequence build' , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode( 'sequence builders' , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode( 'sequence builders' , 'multi-sequence build' , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = '''Encode this sequence.''' SCREAMING_SNAKE_CASE__ : int = tokenizer.byte_encoder[''' '''.encode('utf-8' )[0]] # Testing encoder arguments SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) tokenizer.add_special_tokens({'bos_token': '<s>'} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Testing spaces after special tokens SCREAMING_SNAKE_CASE__ : Any = '''<mask>''' tokenizer.add_special_tokens( {'mask_token': AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ )} ) # mask token has a left space SCREAMING_SNAKE_CASE__ : Any = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = '''Encode <mask> sequence''' SCREAMING_SNAKE_CASE__ : str = '''Encode <mask>sequence''' SCREAMING_SNAKE_CASE__ : int = tokenizer.encode(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = encoded.index(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = encoded.index(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def __lowercase( self : Optional[Any] )-> int: """simple docstring""" pass def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = '''A, <mask> AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ : Any = tokenizer_r.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_p.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ ) # 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__ : List[str] = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( UpperCAmelCase__ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( UpperCAmelCase__ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): SCREAMING_SNAKE_CASE__ : List[str] = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) SCREAMING_SNAKE_CASE__ : str = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['add_prefix_space'] , UpperCAmelCase__ ) self.assertEqual(post_processor_state['add_prefix_space'] , UpperCAmelCase__ ) self.assertEqual(post_processor_state['trim_offsets'] , UpperCAmelCase__ ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" # 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__ : Dict = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE__ : Optional[Any] = F'''{text_of_1_token} {text_of_1_token}''' SCREAMING_SNAKE_CASE__ : Any = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : Tuple = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : List[str] = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ), len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ), len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : Any = 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__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : List[Any] = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ), 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ), 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , )
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : int ): '''simple docstring''' if isinstance(lowercase__ , np.ndarray ): return list(tensor.shape ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.shape(lowercase__ ) if tensor.shape == tf.TensorShape(lowercase__ ): return dynamic SCREAMING_SNAKE_CASE__ : List[Any] = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(lowercase__ )] def _a ( lowercase__ : str , lowercase__ : int = None , lowercase__ : str = None ): '''simple docstring''' return tf.nn.softmax(logits=logits + 1E-9 , axis=lowercase__ , name=lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : Any , lowercase__ : List[str] , lowercase__ : List[Any]=1E-5 , lowercase__ : Dict=-1 ): '''simple docstring''' if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowercase__ , lowercase__ ): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' ) # Get mean and variance on the axis to be normalized SCREAMING_SNAKE_CASE__ : str = tf.nn.moments(lowercase__ , axes=[axis] , keepdims=lowercase__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis SCREAMING_SNAKE_CASE__ : Dict = [1] * inputs.shape.rank SCREAMING_SNAKE_CASE__ : List[Any] = shape_list(lowercase__ )[axis] SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.reshape(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = tf.reshape(lowercase__ , lowercase__ ) # Compute layer normalization using the batch_normalization # function. SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.nn.batch_normalization( lowercase__ , lowercase__ , lowercase__ , offset=lowercase__ , scale=lowercase__ , variance_epsilon=lowercase__ , ) return outputs def _a ( lowercase__ : Dict , lowercase__ : int=0 , lowercase__ : Dict=-1 ): '''simple docstring''' if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input SCREAMING_SNAKE_CASE__ : Dict = tf.shape(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(lowercase__ , lowercase__ ) def _a ( lowercase__ : Dict ): '''simple docstring''' if not isinstance(lowercase__ , tf.Tensor ): SCREAMING_SNAKE_CASE__ : Tuple = tf.convert_to_tensor(lowercase__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: SCREAMING_SNAKE_CASE__ : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) SCREAMING_SNAKE_CASE__ : int = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _a ( lowercase__ : Union[str, Any] , lowercase__ : Any , lowercase__ : List[str] = "input_ids" ): '''simple docstring''' tf.debugging.assert_less( lowercase__ , tf.cast(lowercase__ , dtype=tensor.dtype ) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(lowercase__ )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def _a ( lowercase__ : Optional[Any] , lowercase__ : Dict , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. SCREAMING_SNAKE_CASE__ : Optional[int] = [x for x in data if len(lowercase__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) SCREAMING_SNAKE_CASE__ : Dict = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : str = np.array_split(lowercase__ , lowercase__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array_split(lowercase__ , lowercase__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = chunk_data else: SCREAMING_SNAKE_CASE__ : List[str] = data def _a ( lowercase__ : List[str] , lowercase__ : Tuple ): '''simple docstring''' if name in group.attrs: SCREAMING_SNAKE_CASE__ : Tuple = [n.decode('utf8' ) if hasattr(lowercase__ , 'decode' ) else n for n in group.attrs[name]] else: SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Dict = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8' ) if hasattr(lowercase__ , 'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] ) chunk_id += 1 return data def _a ( lowercase__ : Any ): '''simple docstring''' def _expand_single_ad_tensor(lowercase__ : Dict ): if isinstance(lowercase__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(lowercase__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , lowercase__ )
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : Optional[int] , a_ : str , a_ : Tuple=13 , a_ : Optional[Any]=7 , a_ : Any=True , a_ : Dict=True , a_ : Any=False , a_ : str=True , a_ : Any=99 , a_ : List[Any]=32 , a_ : int=5 , a_ : List[Any]=4 , a_ : Dict=37 , a_ : Optional[Any]="gelu" , a_ : Any=0.1 , a_ : str=0.1 , a_ : List[Any]=512 , a_ : List[Any]=16 , a_ : Any=2 , a_ : Tuple=0.02 , a_ : str=3 , a_ : Dict=4 , a_ : List[Any]=None , )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : List[str] = seq_length SCREAMING_SNAKE_CASE__ : Dict = is_training SCREAMING_SNAKE_CASE__ : Any = use_input_mask SCREAMING_SNAKE_CASE__ : Any = use_token_type_ids SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple = type_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE__ : Any = num_choices SCREAMING_SNAKE_CASE__ : List[str] = scope def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : Optional[int] , a_ : Dict , a_ : int , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Dict , a_ : str , a_ : List[Any] , a_ : Optional[int] , a_ : Union[str, Any] , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : Optional[Any] , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : int , a_ : Tuple , a_ : Tuple , a_ : Any , a_ : Optional[Any] , a_ : List[str] , *a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : int = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : Any = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : int = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def __lowercase( self : Tuple , a_ : Optional[Any] , a_ : int , a_ : Tuple , a_ : Union[str, Any] , a_ : Any , *a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() SCREAMING_SNAKE_CASE__ : str = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def __lowercase( self : int , a_ : Tuple , a_ : List[str] , a_ : Dict , a_ : List[str] , a_ : str , *a_ : Optional[int] , a_ : Dict=False )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : List[Any] , a_ : str , *a_ : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Union[str, Any] , a_ : Optional[Any] , a_ : List[str] , a_ : Dict , a_ : str , a_ : Optional[Any] , *a_ : Union[str, Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Dict = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Union[str, Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def __lowercase( self : Optional[int] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : str = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[str] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Any = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Optional[int] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='pt' , padding=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs['input_ids'].to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs['attention_mask'].to(SCREAMING_SNAKE_CASE_ ) , ) SCREAMING_SNAKE_CASE__ : int = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : str = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Any = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : int )-> Any: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Any = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Tuple = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Any = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Any = model(SCREAMING_SNAKE_CASE_ )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = 4_2384 SCREAMING_SNAKE_CASE__ : Tuple = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Any = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = tokenizer('COVID-19 is' , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : Union[str, Any] , a_ : Any , a_ : int=7 , a_ : Union[str, Any]=3 , a_ : str=18 , a_ : Tuple=30 , a_ : str=400 , a_ : Any=True , a_ : Union[str, Any]=None , a_ : Optional[Any]=True , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_channels SCREAMING_SNAKE_CASE__ : List[str] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = min_resolution SCREAMING_SNAKE_CASE__ : str = max_resolution SCREAMING_SNAKE_CASE__ : Dict = do_resize SCREAMING_SNAKE_CASE__ : Optional[int] = size SCREAMING_SNAKE_CASE__ : List[str] = do_normalize def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804], [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class snake_case ( _snake_case , unittest.TestCase ): lowercase_ = ImageGPTImageProcessor if is_vision_available() else None def __lowercase( self : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ImageGPTImageProcessingTester(self ) @property def __lowercase( self : int )-> List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case_ , 'clusters' ) ) self.assertTrue(hasattr(snake_case_ , 'do_resize' ) ) self.assertTrue(hasattr(snake_case_ , 'size' ) ) self.assertTrue(hasattr(snake_case_ , 'do_normalize' ) ) def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : Dict = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(snake_case_ , obj[key] ) ) else: self.assertEqual(obj[key] , snake_case_ ) def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(snake_case_ , 'image_processor.json' ) image_processor_first.to_json_file(snake_case_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processing_class.from_json_file(snake_case_ ).to_dict() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(snake_case_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , snake_case_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(snake_case_ ) SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class.from_pretrained(snake_case_ ).to_dict() SCREAMING_SNAKE_CASE__ : List[str] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(snake_case_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , snake_case_ ) @unittest.skip('ImageGPT requires clusters at initialization' ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" pass def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) SCREAMING_SNAKE_CASE__ : List[str] = Image.open(dataset[4]['file'] ) SCREAMING_SNAKE_CASE__ : List[str] = Image.open(dataset[5]['file'] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [imagea, imagea] return images @require_vision @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) SCREAMING_SNAKE_CASE__ : Any = prepare_images() # test non-batched SCREAMING_SNAKE_CASE__ : int = image_processing(images[0] , return_tensors='pt' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , snake_case_ ) # test batched SCREAMING_SNAKE_CASE__ : Dict = image_processing(snake_case_ , return_tensors='pt' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) SCREAMING_SNAKE_CASE__ : Any = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , snake_case_ )
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
from __future__ import annotations import os from collections.abc import Mapping SCREAMING_SNAKE_CASE__ : Dict = tuple[int, int] class snake_case : def __init__( self : Optional[int] , a_ : set[int] , a_ : Mapping[EdgeT, int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : set[int] = vertices SCREAMING_SNAKE_CASE__ : dict[EdgeT, int] = { (min(UpperCAmelCase__ ), max(UpperCAmelCase__ )): weight for edge, weight in edges.items() } def __lowercase( self : Any , a_ : EdgeT , a_ : int )-> Any: """simple docstring""" self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) SCREAMING_SNAKE_CASE__ : str = weight def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Graph = Graph({min(self.vertices )} , {} ) SCREAMING_SNAKE_CASE__ : EdgeT SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : EdgeT SCREAMING_SNAKE_CASE__ : int while len(subgraph.vertices ) < len(self.vertices ): SCREAMING_SNAKE_CASE__ : List[Any] = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: SCREAMING_SNAKE_CASE__ : List[Any] = edge SCREAMING_SNAKE_CASE__ : int = weight subgraph.add_edge(UpperCAmelCase__ , UpperCAmelCase__ ) return subgraph def _a ( lowercase__ : str = "p107_network.txt" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = os.path.abspath(os.path.dirname(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : str = os.path.join(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : dict[EdgeT, int] = {} SCREAMING_SNAKE_CASE__ : list[str] SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : int with open(lowercase__ ) as f: SCREAMING_SNAKE_CASE__ : Tuple = f.read().strip().split('\n' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [line.split(',' ) for line in data] for edgea in range(1 , len(lowercase__ ) ): for edgea in range(lowercase__ ): if adjaceny_matrix[edgea][edgea] != "-": SCREAMING_SNAKE_CASE__ : Tuple = int(adjaceny_matrix[edgea][edgea] ) SCREAMING_SNAKE_CASE__ : Graph = Graph(set(range(len(lowercase__ ) ) ) , lowercase__ ) SCREAMING_SNAKE_CASE__ : Graph = graph.prims_algorithm() SCREAMING_SNAKE_CASE__ : int = sum(graph.edges.values() ) SCREAMING_SNAKE_CASE__ : int = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"""{solution() = }""")
700
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowercase_ = FlaxAutoencoderKL @property def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = (32, 32) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.random.uniform(_lowerCamelCase , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } SCREAMING_SNAKE_CASE__ : int = self.dummy_input return init_dict, inputs_dict
701
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class snake_case ( lowerCamelCase__ ): def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE__ : Tuple = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE__ : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value('bool' ) , type=Value('int64' ) ) ) def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = pa.array(TypedSequence([1, 2, 3] , type=Value('int32' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowercase( self : Optional[int] )-> int: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array(TypedSequence(['foo', 'bar'] , type=Value('int64' ) ) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = pa.array(TypedSequence([1, 2, 3] , try_type=Value('int32' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowercase( self : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.array(TypedSequence(['foo', 'bar'] , try_type=Value('int64' ) ) ) self.assertEqual(arr.type , pa.string() ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , 'int64' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , 'int64' ) ) def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE__ : List[str] = pa.array(TypedSequence(['foo', 'bar'] , type=ArrayaD((1, 3) , 'int64' ) ) ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , 'int64' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , 'int64' ) ) def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.array(TypedSequence(['foo', 'bar'] , try_type=ArrayaD((1, 3) , 'int64' ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def __lowercase( self : Dict )-> List[Any]: """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE__ : List[Any] = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' , side_effect=__lowerCamelCase ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] , type=Image() ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' , __lowerCamelCase ) self.assertFalse(kwargs['optimize_list_casting'] ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = pa.BufferReader(lowerCamelCase_ ) if isinstance(lowerCamelCase_ , pa.Buffer ) else pa.memory_map(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = pa.ipc.open_stream(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def _a ( lowercase__ : int , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pa.BufferOutputStream() SCREAMING_SNAKE_CASE__ : Any = pa.schema(lowerCamelCase_ ) if fields else None with ArrowWriter(stream=lowerCamelCase_ , schema=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE__ : Any = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE__ : int = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pa.BufferOutputStream() SCREAMING_SNAKE_CASE__ : Union[str, Any] = Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCamelCase_ , features=lowerCamelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE__ : Tuple = pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.ipc.open_stream(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : pa.Table = f.read_all() SCREAMING_SNAKE_CASE__ : Any = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCamelCase_ ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ , hash_salt='split_name' , check_duplicates=lowerCamelCase_ , ) as writer: with pytest.raises(lowerCamelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=[1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 10] ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ , hash_salt='split_name' , check_duplicates=lowerCamelCase_ , ) as writer: with pytest.raises(lowerCamelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=10 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=10 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 10] ) def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ , hash_salt='split_name' , check_duplicates=lowerCamelCase_ , ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} , key=1 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=2 ) SCREAMING_SNAKE_CASE__ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def _a ( lowercase__ : str , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = pa.BufferOutputStream() SCREAMING_SNAKE_CASE__ : int = pa.schema(lowerCamelCase_ ) if fields else None with ArrowWriter(stream=lowerCamelCase_ , schema=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE__ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE__ : List[Any] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def _a ( lowercase__ : Optional[Any] , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.BufferOutputStream() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.schema(lowerCamelCase_ ) if fields else None with ArrowWriter(stream=lowerCamelCase_ , schema=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE__ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE__ : Dict = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def _a ( lowercase__ : List[Any] , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = pa.BufferOutputStream() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.schema(lowerCamelCase_ ) if fields else None with ArrowWriter(stream=lowerCamelCase_ , schema=lowerCamelCase_ , writer_batch_size=lowerCamelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE__ : Tuple = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase_ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def _a ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Optional[int] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(lowerCamelCase_ , 'test.arrow' ) with ArrowWriter(path=lowerCamelCase_ , schema=pa.schema(lowerCamelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE__ : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCamelCase_ , metadata=writer._schema.metadata ) _check_output(lowerCamelCase_ , 1 ) def _a ( lowercase__ : int ): '''simple docstring''' if pa.types.is_list(lowerCamelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def _a ( lowercase__ : Dict , lowercase__ : List[str] ): '''simple docstring''' if isinstance(lst[0] , lowerCamelCase_ ): change_first_primitive_element_in_list(lst[0] , lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE__ : List[str] = value @pytest.mark.parametrize('optimized_int_type, expected_dtype' , [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def _a ( lowercase__ : List[str] , lowercase__ : int , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = pa.array(TypedSequence(lowerCamelCase_ , optimized_int_type=lowerCamelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype' , [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ] , ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def _a ( lowercase__ : List[Any] , lowercase__ : Optional[Any] , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.array(OptimizedTypedSequence(lowerCamelCase_ , col=lowerCamelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE__ : Union[str, Any] = copy.deepcopy(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Any = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Tuple = pa.array(OptimizedTypedSequence(lowerCamelCase_ , col=lowerCamelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception' , [False, True] ) def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCamelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def _a ( lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''mock://dataset-train.arrow''' with ArrowWriter(path=lowerCamelCase_ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(lowerCamelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCamelCase_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = pa.BufferOutputStream() with ParquetWriter(stream=lowerCamelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE__ : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE__ : List[Any] = pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE__ : pa.Table = pq.read_table(lowerCamelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files' , [False, True] ) def _a ( lowercase__ : int , lowercase__ : List[str] ): '''simple docstring''' import PIL.Image SCREAMING_SNAKE_CASE__ : Optional[int] = str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(lowerCamelCase_ , format='png' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.BufferOutputStream() with ParquetWriter( stream=lowerCamelCase_ , features=Features({'image': Image()} ) , embed_local_files=lowerCamelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE__ : Dict = pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE__ : pa.Table = pq.read_table(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'] , lowerCamelCase_ ) with open(lowerCamelCase_ , 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = pa.schema([pa.field('col_1' , pa.string() , nullable=lowerCamelCase_ )] ) SCREAMING_SNAKE_CASE__ : List[str] = pa.BufferOutputStream() with ArrowWriter(stream=lowerCamelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCamelCase_ ) assert writer._schema == pa.schema([pa.field('col_1' , pa.string() )] )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path SCREAMING_SNAKE_CASE__ : List[str] = [ {"dataset": "wikipedia", "config_name": "20220301.de"}, {"dataset": "wikipedia", "config_name": "20220301.en"}, {"dataset": "wikipedia", "config_name": "20220301.fr"}, {"dataset": "wikipedia", "config_name": "20220301.frr"}, {"dataset": "wikipedia", "config_name": "20220301.it"}, {"dataset": "wikipedia", "config_name": "20220301.simple"}, {"dataset": "snli", "config_name": "plain_text"}, {"dataset": "eli5", "config_name": "LFQA_reddit"}, {"dataset": "wiki40b", "config_name": "en"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.compressed"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.no_index"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.multiset.no_index"}, {"dataset": "natural_questions", "config_name": "default"}, ] def _a ( lowercase__ : Dict=True ): '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=UpperCAmelCase_ ) ) class snake_case ( UpperCAmelCase_ ): lowercase_ = None lowercase_ = None def __lowercase( self : Dict , a_ : Optional[Any] , a_ : Optional[Any] )-> List[Any]: """simple docstring""" with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : List[Any] = dataset_module_factory(_lowercase , cache_dir=_lowercase ) SCREAMING_SNAKE_CASE__ : Dict = import_main_class(dataset_module.module_path , dataset=_lowercase ) SCREAMING_SNAKE_CASE__ : Dict = builder_cls( cache_dir=_lowercase , config_name=_lowercase , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE__ : List[str] = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=_lowercase ).replace(os.sep , '/' ), config.DATASET_INFO_FILENAME, ] ) SCREAMING_SNAKE_CASE__ : int = cached_path(_lowercase , cache_dir=_lowercase ) self.assertTrue(os.path.exists(_lowercase ) ) @pytest.mark.integration def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = tmp_path_factory.mktemp('test_hf_gcp' ) / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE__ : List[str] = dataset_module_factory('wikipedia' , cache_dir=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple = import_main_class(dataset_module.module_path ) SCREAMING_SNAKE_CASE__ : List[str] = builder_cls( cache_dir=UpperCamelCase__ , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE__ : List[Any] = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE__ : Optional[int] = builder_instance.as_dataset() assert ds @pytest.mark.integration def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dataset_module_factory('wikipedia' , cache_dir=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = import_main_class(dataset_module.module_path , dataset=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = builder_cls( cache_dir=UpperCamelCase__ , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE__ : str = builder_instance.as_streaming_dataset() assert ds assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) assert "train" in ds assert isinstance(ds['train'] , UpperCamelCase__ ) assert next(iter(ds['train'] ) )
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''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))
636
0
from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ : str = {"tokenization_wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) class snake_case ( _UpperCAmelCase ): lowercase_ = ['''pixel_values'''] def __init__( self : Optional[int] , a_ : bool = True , a_ : Dict[str, int] = None , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : bool = True , a_ : Dict[str, int] = None , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN , a_ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD , **a_ : Dict , )-> None: """simple docstring""" super().__init__(**A_ ) __A : List[str] = size if size is not None else {'shortest_edge': 224} __A : List[Any] = get_size_dict(A_ , default_to_square=A_ ) __A : Optional[int] = crop_size if crop_size is not None else {'height': 224, 'width': 224} __A : str = get_size_dict(A_ , param_name='crop_size' ) __A : Dict = do_resize __A : Optional[int] = size __A : List[Any] = resample __A : List[Any] = do_center_crop __A : Optional[int] = crop_size __A : int = do_rescale __A : str = rescale_factor __A : Any = do_normalize __A : int = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __A : int = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __lowercase( self : Any , a_ : np.ndarray , a_ : Dict[str, int] , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : int , )-> np.ndarray: """simple docstring""" __A : int = get_size_dict(A_ , default_to_square=A_ ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __A : int = int((256 / 224) * size['shortest_edge'] ) __A : List[Any] = get_resize_output_image_size(A_ , size=A_ , default_to_square=A_ ) __A : List[Any] = {'height': output_size[0], 'width': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F'''Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}''' ) return resize( A_ , size=(size_dict['height'], size_dict['width']) , resample=A_ , data_format=A_ , **A_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> np.ndarray: """simple docstring""" __A : List[str] = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'''Size dict must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def __lowercase( self : List[str] , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Optional[Any] , )-> np.ndarray: """simple docstring""" return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def __lowercase( self : Dict , a_ : np.ndarray , a_ : Union[float, List[float]] , a_ : Union[float, List[float]] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Optional[int] , )-> np.ndarray: """simple docstring""" return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def __lowercase( self : Union[str, Any] , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[Dict[str, int]] = None , a_ : PILImageResampling = None , a_ : Optional[bool] = None , a_ : Optional[Dict[str, int]] = None , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[Union[float, Iterable[float]]] = None , a_ : Optional[Union[float, Iterable[float]]] = None , a_ : Optional[TensorType] = None , a_ : ChannelDimension = ChannelDimension.FIRST , **a_ : Any , )-> BatchFeature: """simple docstring""" __A : int = do_resize if do_resize is not None else self.do_resize __A : int = resample if resample is not None else self.resample __A : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop __A : List[str] = do_rescale if do_rescale is not None else self.do_rescale __A : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor __A : Any = do_normalize if do_normalize is not None else self.do_normalize __A : int = image_mean if image_mean is not None else self.image_mean __A : List[str] = image_std if image_std is not None else self.image_std __A : int = size if size is not None else self.size __A : str = get_size_dict(A_ , default_to_square=A_ ) __A : List[str] = crop_size if crop_size is not None else self.crop_size __A : Union[str, Any] = get_size_dict(A_ , param_name='crop_size' ) __A : Dict = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __A : Any = [to_numpy_array(A_ ) for image in images] if do_resize: __A : Optional[Any] = [self.resize(A_ , A_ , A_ ) for image in images] if do_center_crop: __A : int = [self.center_crop(A_ , A_ ) for image in images] if do_rescale: __A : Optional[Any] = [self.rescale(A_ , A_ ) for image in images] if do_normalize: __A : Optional[Any] = [self.normalize(A_ , A_ , A_ ) for image in images] __A : List[str] = [to_channel_dimension_format(A_ , A_ ) for image in images] __A : Optional[int] = {'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class snake_case ( __lowercase , unittest.TestCase ): lowercase_ = ReformerTokenizer lowercase_ = ReformerTokenizerFast lowercase_ = True lowercase_ = False lowercase_ = True def __lowercase( self : str )-> int: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : Tuple = ReformerTokenizer(a_ , keep_accents=a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "<s>" SCREAMING_SNAKE_CASE__ : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(a_ ) , 1000 ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __lowercase( self : Tuple )-> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : Any = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : List[str] , a_ : List[str]=15 )-> Tuple: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) # Simple input SCREAMING_SNAKE_CASE__ : Union[str, Any] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[Any] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Tuple = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : str = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(a_ , tokenizer_r.encode , a_ , max_length=a_ , padding='max_length' ) # Simple input self.assertRaises(a_ , tokenizer_r.encode_plus , a_ , max_length=a_ , padding='max_length' ) # Simple input self.assertRaises( a_ , tokenizer_r.batch_encode_plus , a_ , max_length=a_ , padding='max_length' , ) # Pair input self.assertRaises(a_ , tokenizer_r.encode , a_ , max_length=a_ , padding='max_length' ) # Pair input self.assertRaises(a_ , tokenizer_r.encode_plus , a_ , max_length=a_ , padding='max_length' ) # Pair input self.assertRaises( a_ , tokenizer_r.batch_encode_plus , a_ , max_length=a_ , padding='max_length' , ) def __lowercase( self : List[Any] )-> int: """simple docstring""" pass def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ReformerTokenizer(a_ , keep_accents=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(a_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a_ ) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE__ : Dict = 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', 'é', '.', ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(a_ ) self.assertListEqual( a_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE__ : List[Any] = 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 __lowercase( self : Dict )-> List[str]: """simple docstring""" return ReformerTokenizer.from_pretrained('google/reformer-crime-and-punishment' ) @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = "Hello World!" SCREAMING_SNAKE_CASE__ : Optional[Any] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) SCREAMING_SNAKE_CASE__ : Tuple = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @require_torch @slow def __lowercase( self : Any )-> int: """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence SCREAMING_SNAKE_CASE__ : str = list(self.big_tokenizer.get_vocab().keys() )[:10] SCREAMING_SNAKE_CASE__ : Optional[Any] = " ".join(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.big_tokenizer.encode_plus(a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Dict = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Tuple = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) SCREAMING_SNAKE_CASE__ : Optional[Any] = encoded_sequence["input_ids"].shape SCREAMING_SNAKE_CASE__ : Optional[Any] = ReformerModel(a_ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**a_ ) model(**a_ ) @slow def __lowercase( self : int )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : str = {"input_ids": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], "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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 SCREAMING_SNAKE_CASE__ : List[Any] = [ "This is a very simple sentence.", "The quick brown fox jumps over the lazy dog.", ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/reformer-crime-and-punishment' , revision='0e6c3decb8211d49bf881013425dc8b0448b3f5a' , padding=a_ , sequences=a_ , )
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( 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 , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = torch.load(lowercase__ , map_location='cpu' ) if "model" in sd.keys(): SCREAMING_SNAKE_CASE__ : Dict = torch.load(lowercase__ , map_location='cpu' )["""model"""] # pop unnecessary weights SCREAMING_SNAKE_CASE__ : Optional[int] = [ """decoder.version""", """decoder.output_projection.weight""", ] for key in keys_to_delete: if key in sd: sd.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { """decoder.project_in_dim.weight""": """decoder.project_in.weight""", """decoder.project_out_dim.weight""": """decoder.project_out.weight""", """decoder.layer_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.layer_norm.bias""": """decoder.final_layer_norm.bias""", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: SCREAMING_SNAKE_CASE__ : List[Any] = sd.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: SCREAMING_SNAKE_CASE__ : List[str] = sd[key] # We split QKV in separate Q,K,V SCREAMING_SNAKE_CASE__ : Any = key.replace('.qkv_proj.' , '.q_proj.' ) SCREAMING_SNAKE_CASE__ : int = key.replace('.qkv_proj.' , '.k_proj.' ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace('.qkv_proj.' , '.v_proj.' ) SCREAMING_SNAKE_CASE__ : List[str] = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 SCREAMING_SNAKE_CASE__ : Dict = torch.split(lowercase__ , depth // 3 , dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = q SCREAMING_SNAKE_CASE__ : Any = k SCREAMING_SNAKE_CASE__ : int = v del sd[key] return sd @torch.no_grad() def _a ( lowercase__ : Optional[Any] , lowercase__ : int , lowercase__ : Union[str, Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = load_checkpoint(lowercase__ ) if config is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = OPTConfig.from_pretrained(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : Any = OPTConfig() SCREAMING_SNAKE_CASE__ : Dict = OPTModel(lowercase__ ).half().eval() model.load_state_dict(lowercase__ ) # Check results Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fairseq_path", type=str, help=( "path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:" " https://huggingface.co/models?other=opt_metasq" ), ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--hf_config", default=None, type=str, help="Define HF config.") SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): SCREAMING_SNAKE_CASE__ : List[Any] = "pt" elif is_tf_available(): SCREAMING_SNAKE_CASE__ : int = "tf" else: SCREAMING_SNAKE_CASE__ : int = "jax" class snake_case ( __A , unittest.TestCase ): lowercase_ = ByTaTokenizer lowercase_ = False def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" return ByTaTokenizer.from_pretrained('google/byt5-small' ) def __lowercase( self : List[Any] , **a_ : List[Any] )-> List[Any]: """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : Optional[Any]=False , a_ : int=20 , a_ : Optional[int]=5 )-> Optional[Any]: """simple docstring""" # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for ByT5 because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. SCREAMING_SNAKE_CASE__ : str = [] for i in range(len(UpperCamelCase__ ) ): try: SCREAMING_SNAKE_CASE__ : int = tokenizer.decode([i] , clean_up_tokenization_spaces=UpperCamelCase__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(filter(lambda a_ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ : Any = list(filter(lambda a_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=UpperCamelCase__ ) , UpperCamelCase__ ) ) if max_length is not None and len(UpperCamelCase__ ) > max_length: SCREAMING_SNAKE_CASE__ : Tuple = toks[:max_length] if min_length is not None and len(UpperCamelCase__ ) < min_length and len(UpperCamelCase__ ) > 0: while len(UpperCamelCase__ ) < min_length: SCREAMING_SNAKE_CASE__ : Dict = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE__ : Any = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ ) if " " not in output_txt and len(UpperCamelCase__ ) > 1: SCREAMING_SNAKE_CASE__ : Optional[int] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=UpperCamelCase__ ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=UpperCamelCase__ ) ) if with_prefix_space: SCREAMING_SNAKE_CASE__ : str = ' ' + output_txt SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) return output_txt, output_ids def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : Any = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : Optional[Any] = 'Unicode €.' SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'] , UpperCamelCase__ ) # decoding SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , 'Unicode €.</s>' ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer('e è é ê ë' ) SCREAMING_SNAKE_CASE__ : Any = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'] , UpperCamelCase__ ) # decoding SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off SCREAMING_SNAKE_CASE__ : Any = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE__ : List[str] = list(batch.input_ids.numpy()[0] ) else: SCREAMING_SNAKE_CASE__ : str = list(batch.input_ids.tolist()[0] ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def __lowercase( self : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , UpperCamelCase__ ) self.assertIn('attention_mask' , UpperCamelCase__ ) self.assertNotIn('decoder_input_ids' , UpperCamelCase__ ) self.assertNotIn('decoder_attention_mask' , UpperCamelCase__ ) def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : str = [ 'Summary of the text.', 'Another summary.', ] SCREAMING_SNAKE_CASE__ : Dict = tokenizer( text_target=UpperCamelCase__ , max_length=32 , padding='max_length' , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def __lowercase( self : Dict )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.ta_base_tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = ['A long paragraph for summarization. </s>'] SCREAMING_SNAKE_CASE__ : int = ['Summary of the text. </s>'] # fmt: off SCREAMING_SNAKE_CASE__ : Optional[Any] = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] SCREAMING_SNAKE_CASE__ : str = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on SCREAMING_SNAKE_CASE__ : Dict = tokenizer(UpperCamelCase__ , text_target=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , batch['input_ids'][0] ) self.assertEqual(UpperCamelCase__ , batch['labels'][0] ) def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" # safety check on max_len default value so we are sure the test works SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = ' He is very happy, UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) tokenizer.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int = tokenizer.__class__.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = after_tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) shutil.rmtree(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE__ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) tokenizer.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.__class__.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int = after_tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.__class__.from_pretrained(UpperCamelCase__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(UpperCamelCase__ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: SCREAMING_SNAKE_CASE__ : Any = json.load(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: SCREAMING_SNAKE_CASE__ : Optional[int] = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = [F'''<extra_id_{i}>''' for i in range(125 )] SCREAMING_SNAKE_CASE__ : int = added_tokens_extra_ids + [ 'an_additional_special_token' ] SCREAMING_SNAKE_CASE__ : List[Any] = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(UpperCamelCase__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(UpperCamelCase__ , UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(UpperCamelCase__ , UpperCamelCase__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class.from_pretrained( UpperCamelCase__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE__ : Tuple = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_class.from_pretrained( UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_class.from_pretrained(UpperCamelCase__ ) self.assertTrue(tokenizer.decode([255] ) == '' ) def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" pass def __lowercase( self : Dict )-> str: """simple docstring""" pass def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" pass def __lowercase( self : List[str] )-> int: """simple docstring""" pass def __lowercase( self : Tuple )-> List[str]: """simple docstring""" # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings # and special added tokens as tokens SCREAMING_SNAKE_CASE__ : int = self.get_tokenizers(fast=UpperCamelCase__ , do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : Optional[int] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.convert_tokens_to_string(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : Dict = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Dict = tokenizer.convert_ids_to_tokens( UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) for attr in attributes_list: setattr(UpperCamelCase__ , attr + '_id' , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , attr + '_id' ) , UpperCamelCase__ ) setattr(UpperCamelCase__ , attr + '_id' , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , attr + '_id' ) , UpperCamelCase__ ) setattr(UpperCamelCase__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(UpperCamelCase__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(UpperCamelCase__ , 'additional_special_tokens_ids' ) , [] ) setattr(UpperCamelCase__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(UpperCamelCase__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(UpperCamelCase__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets SCREAMING_SNAKE_CASE__ : str = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n" SCREAMING_SNAKE_CASE__ : str = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n" SCREAMING_SNAKE_CASE__ : Union[str, Any] = r"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {\'accuracy\': 1.0}\n" @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def __lowercase( self : Optional[int] , a_ : Optional[int] , a_ : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 0.0 for i, j in zip(lowerCamelCase_ , lowerCamelCase_ ): n_correct += 1.0 if math_equivalence.is_equiv(lowerCamelCase_ , lowerCamelCase_ ) else 0.0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = n_correct / len(lowerCamelCase_ ) return { "accuracy": accuracy, }
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
SCREAMING_SNAKE_CASE__ : Dict = "0.18.2" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
711
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : Dict=1.0 , lowercase__ : int=None , lowercase__ : Union[str, Any]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : Dict , a_ : List[Any] , a_ : List[str]=7 , a_ : Any=400 , a_ : Tuple=2000 , a_ : List[str]=1 , a_ : List[Any]=0.0 , a_ : Tuple=1_6000 , a_ : Union[str, Any]=True , a_ : str=80 , a_ : List[str]=16 , a_ : List[str]=64 , a_ : Optional[Any]="hann_window" , a_ : Tuple=80 , a_ : str=7600 , a_ : Any=1e-1_0 , a_ : int=True , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : Optional[int] = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : Any = feature_size SCREAMING_SNAKE_CASE__ : List[Any] = padding_value SCREAMING_SNAKE_CASE__ : List[str] = sampling_rate SCREAMING_SNAKE_CASE__ : Dict = do_normalize SCREAMING_SNAKE_CASE__ : Optional[int] = num_mel_bins SCREAMING_SNAKE_CASE__ : str = hop_length SCREAMING_SNAKE_CASE__ : Tuple = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : str = fmin SCREAMING_SNAKE_CASE__ : Any = fmax SCREAMING_SNAKE_CASE__ : List[str] = mel_floor SCREAMING_SNAKE_CASE__ : Union[str, Any] = return_attention_mask def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : Dict , a_ : List[Any]=False , a_ : Union[str, Any]=False )-> List[str]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*lowerCAmelCase_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : List[Any] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Dict = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[Any] = [np.asarray(lowerCAmelCase_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Dict , a_ : str=False , a_ : str=False )-> Dict: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Dict = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : Tuple = [np.asarray(lowerCAmelCase_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : List[Any] , a_ : Optional[int] )-> Any: """simple docstring""" self.assertTrue(np.all(np.mean(lowerCAmelCase_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(lowerCAmelCase_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : int = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Any = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Any = feat_extract(lowerCAmelCase_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(lowerCAmelCase_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) def __lowercase( self : Union[str, Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : str = [None, 1600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(lowerCAmelCase_ , padding=lowerCAmelCase_ , max_length=lowerCAmelCase_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : int = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : str = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Dict = [None, 1600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): SCREAMING_SNAKE_CASE__ : Dict = feat_extract(lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Any = [np.asarray(lowerCAmelCase_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : int = feature_extractor(audio_target=lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Dict = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : int = feature_extractor(lowerCAmelCase_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(lowerCAmelCase_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : Tuple = np.asarray(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(lowerCAmelCase_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(lowerCAmelCase_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : str = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) for x, y in zip(lowerCAmelCase_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.prepare_inputs_for_target(equal_length=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[str] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feat_extract_tester.prepare_inputs_for_target(equal_length=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : int = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : List[str] = feat_extract.pad(lowerCAmelCase_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract.pad(lowerCAmelCase_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Dict = [len(lowerCAmelCase_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : int = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad(lowerCAmelCase_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , lowerCAmelCase_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , lowerCAmelCase_ ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Optional[int] = [len(lowerCAmelCase_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Tuple = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Dict = feat_extract.pad( lowerCAmelCase_ , padding='max_length' , max_length=lowerCAmelCase_ , truncation=lowerCAmelCase_ , return_tensors='np' ) self.assertIn('attention_mask' , lowerCAmelCase_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : int , a_ : List[str] )-> List[str]: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : str = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : Union[str, Any] = ds.sort('id' ).select(range(lowerCAmelCase_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Dict = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(lowerCAmelCase_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , lowerCAmelCase_ , atol=1e-6 ) ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Any = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=lowerCAmelCase_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , lowerCAmelCase_ , atol=1e-4 ) )
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = len(a_ ) + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(a_ ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Optional[int] = [[0 for i in range(a_ )] for j in range(a_ )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : str = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , a_ ): SCREAMING_SNAKE_CASE__ : Tuple = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , a_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , a_ ): for j in range(1 , a_ ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Dict = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : Tuple = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") SCREAMING_SNAKE_CASE__ : str = "aab" SCREAMING_SNAKE_CASE__ : Optional[int] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F"""{input_string} matches the given pattern {pattern}""") else: print(F"""{input_string} does not match with the given pattern {pattern}""")
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Tuple = { "configuration_pegasus_x": ["PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusXConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST", "PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
from abc import ABC, abstractmethod from typing import List, Optional class snake_case ( UpperCamelCase_ ): def __init__( self : List[str] )-> Tuple: """simple docstring""" # test for the above condition self.test() def __lowercase( self : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = False while not completed: if counter == 1: self.reset() SCREAMING_SNAKE_CASE__ : List[Any] = self.advance() if not self.does_advance(__UpperCamelCase ): raise Exception( 'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = self.update(__UpperCamelCase ) counter += 1 if counter > 1_0000: raise Exception('update() does not fulfill the constraint.' ) if self.remaining() != 0: raise Exception('Custom Constraint is not defined correctly.' ) @abstractmethod def __lowercase( self : str )-> Optional[int]: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def __lowercase( self : Optional[int] , a_ : int )-> Optional[int]: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def __lowercase( self : Union[str, Any] , a_ : int )-> Any: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def __lowercase( self : List[str] )-> int: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def __lowercase( self : str , a_ : List[str]=False )-> int: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case ( UpperCamelCase_ ): def __init__( self : Tuple , a_ : List[int] )-> Union[str, Any]: """simple docstring""" super(__UpperCamelCase , self ).__init__() if not isinstance(__UpperCamelCase , __UpperCamelCase ) or len(__UpperCamelCase ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(__UpperCamelCase , __UpperCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) SCREAMING_SNAKE_CASE__ : Any = token_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = len(self.token_ids ) SCREAMING_SNAKE_CASE__ : Optional[int] = -1 # the index of the currently fulfilled step SCREAMING_SNAKE_CASE__ : Optional[Any] = False def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def __lowercase( self : List[Any] , a_ : int )-> Any: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__UpperCamelCase )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def __lowercase( self : int , a_ : int )-> Tuple: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__UpperCamelCase )}''' ) SCREAMING_SNAKE_CASE__ : Dict = False SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False if self.does_advance(__UpperCamelCase ): self.fulfilled_idx += 1 SCREAMING_SNAKE_CASE__ : Tuple = True if self.fulfilled_idx == (self.seqlen - 1): SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Dict = completed else: # failed to make progress. SCREAMING_SNAKE_CASE__ : Optional[Any] = True self.reset() return stepped, completed, reset def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def __lowercase( self : int , a_ : Union[str, Any]=False )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = PhrasalConstraint(self.token_ids ) if stateful: SCREAMING_SNAKE_CASE__ : int = self.seqlen SCREAMING_SNAKE_CASE__ : str = self.fulfilled_idx SCREAMING_SNAKE_CASE__ : Any = self.completed return new_constraint class snake_case : def __init__( self : int , a_ : List[List[int]] , a_ : str=True )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = max([len(__UpperCamelCase ) for one in nested_token_ids] ) SCREAMING_SNAKE_CASE__ : List[Any] = {} for token_ids in nested_token_ids: SCREAMING_SNAKE_CASE__ : List[Any] = root for tidx, token_id in enumerate(__UpperCamelCase ): if token_id not in level: SCREAMING_SNAKE_CASE__ : int = {} SCREAMING_SNAKE_CASE__ : Dict = level[token_id] if no_subsets and self.has_subsets(__UpperCamelCase , __UpperCamelCase ): raise ValueError( 'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is' F''' {nested_token_ids}.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = root def __lowercase( self : List[str] , a_ : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.trie for current_token in current_seq: SCREAMING_SNAKE_CASE__ : Any = start[current_token] SCREAMING_SNAKE_CASE__ : int = list(start.keys() ) return next_tokens def __lowercase( self : int , a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.next_tokens(__UpperCamelCase ) return len(__UpperCamelCase ) == 0 def __lowercase( self : List[Any] , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = list(root.values() ) if len(__UpperCamelCase ) == 0: return 1 else: return sum([self.count_leaves(__UpperCamelCase ) for nn in next_nodes] ) def __lowercase( self : List[str] , a_ : str , a_ : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.count_leaves(__UpperCamelCase ) return len(__UpperCamelCase ) != leaf_count class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : List[List[int]] )-> List[str]: """simple docstring""" super(__UpperCamelCase , self ).__init__() if not isinstance(__UpperCamelCase , __UpperCamelCase ) or len(__UpperCamelCase ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(__UpperCamelCase , __UpperCamelCase ) for token_ids in nested_token_ids ): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(__UpperCamelCase , __UpperCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) SCREAMING_SNAKE_CASE__ : int = DisjunctiveTrie(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = nested_token_ids SCREAMING_SNAKE_CASE__ : Optional[int] = self.trie.max_height SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Tuple = False def __lowercase( self : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.trie.next_tokens(self.current_seq ) if len(__UpperCamelCase ) == 0: return None else: return token_list def __lowercase( self : Any , a_ : int )-> List[Any]: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase )}''' ) SCREAMING_SNAKE_CASE__ : str = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def __lowercase( self : Optional[int] , a_ : int )-> Optional[int]: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase )}''' ) SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : str = False if self.does_advance(__UpperCamelCase ): self.current_seq.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : int = True else: SCREAMING_SNAKE_CASE__ : List[Any] = True self.reset() SCREAMING_SNAKE_CASE__ : str = self.trie.reached_leaf(self.current_seq ) SCREAMING_SNAKE_CASE__ : str = completed return stepped, completed, reset def __lowercase( self : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = False SCREAMING_SNAKE_CASE__ : Any = [] def __lowercase( self : str )-> int: """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def __lowercase( self : str , a_ : int=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = DisjunctiveConstraint(self.token_ids ) if stateful: SCREAMING_SNAKE_CASE__ : int = self.seqlen SCREAMING_SNAKE_CASE__ : Tuple = self.current_seq SCREAMING_SNAKE_CASE__ : List[Any] = self.completed return new_constraint class snake_case : def __init__( self : Tuple , a_ : List[Constraint] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = constraints # max # of steps required to fulfill a given constraint SCREAMING_SNAKE_CASE__ : Dict = max([c.seqlen for c in constraints] ) SCREAMING_SNAKE_CASE__ : str = len(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = False self.init_state() def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = [constraint.copy(stateful=__UpperCamelCase ) for constraint in self.constraints] def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" SCREAMING_SNAKE_CASE__ : Optional[Any] = constraint.advance() if isinstance(__UpperCamelCase , __UpperCamelCase ): token_list.append(__UpperCamelCase ) elif isinstance(__UpperCamelCase , __UpperCamelCase ): token_list.extend(__UpperCamelCase ) else: SCREAMING_SNAKE_CASE__ : int = self.inprogress_constraint.advance() if isinstance(__UpperCamelCase , __UpperCamelCase ): token_list.append(__UpperCamelCase ) elif isinstance(__UpperCamelCase , __UpperCamelCase ): token_list.extend(__UpperCamelCase ) if len(__UpperCamelCase ) == 0: return None else: return token_list def __lowercase( self : int , a_ : Optional[List[int]] )-> Optional[Any]: """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.add(__UpperCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def __lowercase( self : Union[str, Any] , a_ : int )-> List[Any]: """simple docstring""" if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = False, False if self.completed: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.inprogress_constraint.update(__UpperCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) SCREAMING_SNAKE_CASE__ : List[str] = None if len(self.pending_constraints ) == 0: # we're done! SCREAMING_SNAKE_CASE__ : int = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__UpperCamelCase ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = pending_constraint.update(__UpperCamelCase ) if not stepped: raise Exception( '`constraint.update(token_id)` is not yielding incremental progress, ' 'even though `constraint.does_advance(token_id)` is true.' ) if complete: self.complete_constraints.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : int = None if not complete and stepped: SCREAMING_SNAKE_CASE__ : Optional[int] = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". SCREAMING_SNAKE_CASE__ : Tuple = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. SCREAMING_SNAKE_CASE__ : Tuple = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def __lowercase( self : Optional[int] , a_ : List[Any]=True )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: SCREAMING_SNAKE_CASE__ : Dict = [ constraint.copy(stateful=__UpperCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: SCREAMING_SNAKE_CASE__ : int = self.inprogress_constraint.copy(stateful=__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [constraint.copy() for constraint in self.pending_constraints] return new_state
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Union[str, Any] , a_ : Tuple , a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Union[str, Any] , a_ : Tuple )-> Tuple: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : List[str] )-> List[str]: """simple docstring""" return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : Any , a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[Any] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : Dict , a_ : List[str] )-> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : str = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Dict = nn.ModuleDict(a_ ) def __lowercase( self : int , a_ : Any )-> List[str]: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Tuple , a_ : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : str , a_ : List[str] )-> Optional[Any]: """simple docstring""" if x not in self: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : List[Any] , a_ : Any )-> Dict: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Dict = RegNetModel else: SCREAMING_SNAKE_CASE__ : str = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[int] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(_UpperCamelCase ).eval() SCREAMING_SNAKE_CASE__ : List[str] = ModuleTransfer(src=_UpperCamelCase , dest=_UpperCamelCase , raise_if_mismatch=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : int = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(_UpperCamelCase ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Union[str, Any] = manually_copy_vissl_head(_UpperCamelCase , our_model.state_dict() , _UpperCamelCase ) our_model.load_state_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = our_model(_UpperCamelCase , output_hidden_states=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = ( our_outputs.logits if isinstance(_UpperCamelCase , _UpperCamelCase ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = from_output[-1] if type(_UpperCamelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : str = our_outputs.hidden_states[-1] assert torch.allclose(_UpperCamelCase , _UpperCamelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=_UpperCamelCase , ) SCREAMING_SNAKE_CASE__ : List[str] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : str = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=_UpperCamelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=_UpperCamelCase , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : List[Any] = 10_00 SCREAMING_SNAKE_CASE__ : Union[str, Any] = (1, num_labels) SCREAMING_SNAKE_CASE__ : Dict = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = json.load(open(cached_download(hf_hub_url(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(_UpperCamelCase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : int = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial(_UpperCamelCase , num_labels=_UpperCamelCase , idalabel=_UpperCamelCase , labelaid=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Optional[Any] = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(_UpperCamelCase , model_dir=str(_UpperCamelCase ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Dict = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : Dict = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_state_dict['trunk'] model.load_state_dict(_UpperCamelCase ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : List[Any] = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : str = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[str] = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : Optional[int] = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Dict = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : str = partial( _UpperCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( _UpperCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , _UpperCamelCase , _UpperCamelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( _UpperCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() SCREAMING_SNAKE_CASE__ : Optional[int] = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ( __UpperCAmelCase ): lowercase_ = '' lowercase_ = 'hf-legacy' # "hf://"" is reserved for hffs def __init__( self : Union[str, Any] , a_ : Optional[int] = None , a_ : Tuple = None , **a_ : Optional[int] , )-> List[str]: """simple docstring""" super().__init__(self , **a_ ) SCREAMING_SNAKE_CASE__ : List[str] = repo_info SCREAMING_SNAKE_CASE__ : str = token SCREAMING_SNAKE_CASE__ : Optional[int] = None def __lowercase( self : Tuple )-> Tuple: """simple docstring""" if self.dir_cache is None: SCREAMING_SNAKE_CASE__ : List[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE__ : str = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(a_ ): {'name': str(a_ ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __lowercase( self : List[str] , a_ : List[Any] , a_ : Union[str, Any] = "rb" , **a_ : Optional[int] , )-> Any: """simple docstring""" if not isinstance(self.repo_info , a_ ): raise NotImplementedError(F'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_url(self.repo_info.id , a_ , revision=self.repo_info.sha ) return fsspec.open( a_ , mode=a_ , headers=get_authentication_headers_for_url(a_ , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def __lowercase( self : str , a_ : List[Any] , **a_ : Optional[int] )-> str: """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE__ : Tuple = self._strip_protocol(a_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a_ ) def __lowercase( self : str , a_ : Tuple , a_ : int=False , **a_ : List[Any] )-> Optional[int]: """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE__ : int = PurePosixPath(path.strip('/' ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE__ : Optional[int] = PurePosixPath(p.strip('/' ) ) SCREAMING_SNAKE_CASE__ : Any = p.parent if root == path: SCREAMING_SNAKE_CASE__ : Any = f SCREAMING_SNAKE_CASE__ : Optional[Any] = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = 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_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" 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 __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) def _a ( lowercase__ : bool , lowercase__ : bool ): '''simple docstring''' def run_func(lowercase__ : List[Any] ): @wraps(lowercase__ ) def run_in_eager_mode(*lowercase__ : Optional[Any] , **lowercase__ : Dict ): return func(*lowercase__ , **lowercase__ ) @wraps(lowercase__ ) @tf.function(experimental_compile=lowercase__ ) def run_in_graph_mode(*lowercase__ : int , **lowercase__ : str ): return func(*lowercase__ , **lowercase__ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( 'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = random.Random() SCREAMING_SNAKE_CASE__ : List[str] = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowercase__ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class snake_case ( __lowerCAmelCase ): lowercase_ = 42 lowercase_ = 42 lowercase_ = "TensorFlow" @property def __lowercase( self : Union[str, Any] )-> List[str]: """simple docstring""" return tf.__version__ def __lowercase( self : Optional[Any] , a_ : str , a_ : int , a_ : int )-> float: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) SCREAMING_SNAKE_CASE__ : Tuple = self._prepare_inference_func(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return self._measure_speed(_inference ) def __lowercase( self : Optional[Any] , a_ : str , a_ : int , a_ : int )-> float: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) SCREAMING_SNAKE_CASE__ : str = self._prepare_train_func(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return self._measure_speed(_train ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : int , a_ : int )-> [Memory, Optional[MemorySummary]]: """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : int = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_inference_func(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return self._measure_memory(_inference ) def __lowercase( self : Tuple , a_ : str , a_ : int , a_ : int )-> [Memory, Optional[MemorySummary]]: """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._prepare_train_func(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return self._measure_memory(_train ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : int , a_ : int )-> Callable[[], None]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) SCREAMING_SNAKE_CASE__ : int = ( hasattr(lowerCamelCase__ , 'architectures' ) and isinstance(config.architectures , lowerCamelCase__ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE__ : List[Any] = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE__ : int = __import__('transformers' , fromlist=[model_class] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(lowerCamelCase__ , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_cls(lowerCamelCase__ ) except ImportError: raise ImportError( F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = TF_MODEL_MAPPING[config.__class__](lowerCamelCase__ ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE__ : int = config.vocab_size if hasattr(lowerCamelCase__ , 'vocab_size' ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE__ : str = random_input_ids(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ , training=lowerCamelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(lowerCamelCase__ , training=lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def __lowercase( self : Tuple , a_ : str , a_ : int , a_ : int )-> Callable[[], None]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' ) if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ( hasattr(lowerCamelCase__ , 'architectures' ) and isinstance(config.architectures , lowerCamelCase__ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE__ : Any = __import__('transformers' , fromlist=[model_class] ) SCREAMING_SNAKE_CASE__ : Any = getattr(lowerCamelCase__ , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = model_cls(lowerCamelCase__ ) except ImportError: raise ImportError( F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' ) else: SCREAMING_SNAKE_CASE__ : List[Any] = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](lowerCamelCase__ ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE__ : Any = config.vocab_size if hasattr(lowerCamelCase__ , 'vocab_size' ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE__ : str = random_input_ids(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): SCREAMING_SNAKE_CASE__ : str = model(lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ , labels=lowerCamelCase__ , training=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE__ : int = tf.gradients(lowerCamelCase__ , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(lowerCamelCase__ , labels=lowerCamelCase__ , training=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE__ : Any = tf.gradients(lowerCamelCase__ , model.trainable_variables ) return gradients SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def __lowercase( self : Tuple , a_ : Union[str, Any] )-> float: """simple docstring""" with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' ) timeit.repeat(lowerCamelCase__ , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average SCREAMING_SNAKE_CASE__ : Optional[Any] = timeit.repeat( lowerCamelCase__ , repeat=self.args.repeat , number=10 , ) return min(lowerCamelCase__ ) / 10.0 except ResourceExhaustedError as e: self.print_fn(F'''Doesn\'t fit on GPU. {e}''' ) def __lowercase( self : Union[str, Any] , a_ : Callable[[], None] )-> [Memory, MemorySummary]: """simple docstring""" logger.info( 'Note that TensorFlow allocates more memory than ' 'it might need to speed up computation. ' 'The memory reported here corresponds to the memory ' 'reported by `nvidia-smi`, which can vary depending ' 'on total available memory on the GPU that is used.' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory' ' consumption line by line.' ) SCREAMING_SNAKE_CASE__ : List[str] = start_memory_tracing('transformers' ) if self.args.is_tpu: # tpu raise NotImplementedError( 'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking' ' with `args.memory=False`' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( 'py3nvml not installed, we won\'t log GPU memory usage. ' 'Install py3nvml (pip install py3nvml) to log information about GPU.' ) SCREAMING_SNAKE_CASE__ : Any = '''N/A''' else: logger.info( 'Measuring total GPU usage on GPU device. Make sure to not have additional processes' ' running on the same GPU.' ) # init nvml nvml.nvmlInit() func() SCREAMING_SNAKE_CASE__ : List[str] = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) SCREAMING_SNAKE_CASE__ : Tuple = nvml.nvmlDeviceGetMemoryInfo(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = meminfo.used SCREAMING_SNAKE_CASE__ : int = Memory(lowerCamelCase__ ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( 'When enabling line by line tracing, the max peak memory for CPU is inaccurate in' ' TensorFlow.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = measure_peak_memory_cpu(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = Memory(lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else memory_bytes if self.args.trace_memory_line_by_line: SCREAMING_SNAKE_CASE__ : Tuple = stop_memory_tracing(lowerCamelCase__ ) if memory is None: SCREAMING_SNAKE_CASE__ : Dict = summary.total else: SCREAMING_SNAKE_CASE__ : Tuple = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F'''Doesn\'t fit on GPU. {e}''' ) return "N/A", None
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base' ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained('xlm-roberta-base' ) SCREAMING_SNAKE_CASE__ : Dict = '''The dog is cute and lives in the garden house''' SCREAMING_SNAKE_CASE__ : List[str] = jnp.array([tokenizer.encode(a_ )] ) SCREAMING_SNAKE_CASE__ : int = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim SCREAMING_SNAKE_CASE__ : Dict = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) SCREAMING_SNAKE_CASE__ : str = model(a_ )['''last_hidden_state'''] self.assertEqual(output.shape , a_ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , a_ , atol=1e-3 ) )
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
from __future__ import annotations class snake_case : def __init__( self : Tuple , a_ : str , a_ : Dict )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = text, pattern SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = len(a_ ), len(a_ ) def __lowercase( self : List[Any] , a_ : List[Any] )-> List[Any]: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __lowercase( self : str , a_ : Tuple )-> List[Any]: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __lowercase( self : Optional[int] )-> List[str]: """simple docstring""" # searches pattern in text and returns index positions SCREAMING_SNAKE_CASE__ : Optional[int] = [] for i in range(self.textLen - self.patLen + 1 ): SCREAMING_SNAKE_CASE__ : List[str] = self.mismatch_in_text(a_ ) if mismatch_index == -1: positions.append(a_ ) else: SCREAMING_SNAKE_CASE__ : List[str] = self.match_in_pattern(self.text[mismatch_index] ) SCREAMING_SNAKE_CASE__ : List[Any] = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions SCREAMING_SNAKE_CASE__ : Tuple = """ABAABA""" SCREAMING_SNAKE_CASE__ : Optional[int] = """AB""" SCREAMING_SNAKE_CASE__ : List[str] = BoyerMooreSearch(text, pattern) SCREAMING_SNAKE_CASE__ : List[Any] = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
def _a ( lowercase__ : Optional[int] , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = '' for word_or_phrase in separated: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise Exception('join() accepts only strings to be joined' ) joined += word_or_phrase + separator return joined.strip(lowerCamelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
import functools def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(lowercase__ ) @functools.cache def min_distance(lowercase__ : int , lowercase__ : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa SCREAMING_SNAKE_CASE__ : int = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , lowercase__ ) , 1 + min_distance(lowercase__ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
700
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger("transformers.models.speecht5") SCREAMING_SNAKE_CASE__ : List[Any] = { "speech_encoder_prenet.layer_norm": "speecht5.encoder.prenet.feature_projection.layer_norm", "speech_encoder_prenet.post_extract_proj": "speecht5.encoder.prenet.feature_projection.projection", "speech_encoder_prenet.pos_conv.0": "speecht5.encoder.prenet.pos_conv_embed.conv", "speech_encoder_prenet.mask_emb": "speecht5.encoder.prenet.masked_spec_embed", } SCREAMING_SNAKE_CASE__ : List[str] = { "text_encoder_prenet.encoder_prenet.0": "speecht5.encoder.prenet.embed_tokens", "text_encoder_prenet.encoder_prenet.1.alpha": "speecht5.encoder.prenet.encode_positions.alpha", } SCREAMING_SNAKE_CASE__ : Optional[Any] = { "speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0": "speecht5.decoder.prenet.layers.0", "speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0": "speecht5.decoder.prenet.layers.1", "speech_decoder_prenet.decoder_prenet.0.1": "speecht5.decoder.prenet.final_layer", "speech_decoder_prenet.decoder_prenet.1.alpha": "speecht5.decoder.prenet.encode_positions.alpha", "speech_decoder_prenet.spkembs_layer.0": "speecht5.decoder.prenet.speaker_embeds_layer", } SCREAMING_SNAKE_CASE__ : Any = { "speech_decoder_postnet.feat_out": "speech_decoder_postnet.feat_out", "speech_decoder_postnet.prob_out": "speech_decoder_postnet.prob_out", "speech_decoder_postnet.postnet.postnet.0.0": "speech_decoder_postnet.layers.0.conv", "speech_decoder_postnet.postnet.postnet.0.1": "speech_decoder_postnet.layers.0.batch_norm", "speech_decoder_postnet.postnet.postnet.1.0": "speech_decoder_postnet.layers.1.conv", "speech_decoder_postnet.postnet.postnet.1.1": "speech_decoder_postnet.layers.1.batch_norm", "speech_decoder_postnet.postnet.postnet.2.0": "speech_decoder_postnet.layers.2.conv", "speech_decoder_postnet.postnet.postnet.2.1": "speech_decoder_postnet.layers.2.batch_norm", "speech_decoder_postnet.postnet.postnet.3.0": "speech_decoder_postnet.layers.3.conv", "speech_decoder_postnet.postnet.postnet.3.1": "speech_decoder_postnet.layers.3.batch_norm", "speech_decoder_postnet.postnet.postnet.4.0": "speech_decoder_postnet.layers.4.conv", "speech_decoder_postnet.postnet.postnet.4.1": "speech_decoder_postnet.layers.4.batch_norm", } SCREAMING_SNAKE_CASE__ : int = { "text_decoder_prenet.embed_tokens": "speecht5.decoder.prenet.embed_tokens", } SCREAMING_SNAKE_CASE__ : int = { "text_decoder_postnet.output_projection": "text_decoder_postnet.lm_head", } SCREAMING_SNAKE_CASE__ : Optional[int] = { "encoder.layers.*.self_attn.k_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj", "encoder.layers.*.self_attn.v_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj", "encoder.layers.*.self_attn.q_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj", "encoder.layers.*.self_attn.out_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj", "encoder.layers.*.self_attn_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.layer_norm", "encoder.layers.*.fc1": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense", "encoder.layers.*.fc2": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense", "encoder.layers.*.final_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm", "encoder.layer_norm": "speecht5.encoder.wrapped_encoder.layer_norm", "encoder.pos_emb.pe_k": "speecht5.encoder.wrapped_encoder.embed_positions.pe_k", } SCREAMING_SNAKE_CASE__ : Dict = { "decoder.layers.*.self_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj", "decoder.layers.*.self_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj", "decoder.layers.*.self_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj", "decoder.layers.*.self_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj", "decoder.layers.*.self_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm", "decoder.layers.*.encoder_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj", "decoder.layers.*.encoder_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj", "decoder.layers.*.encoder_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj", "decoder.layers.*.encoder_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj", "decoder.layers.*.encoder_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm", "decoder.layers.*.fc1": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense", "decoder.layers.*.fc2": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense", "decoder.layers.*.final_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm", } SCREAMING_SNAKE_CASE__ : int = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } SCREAMING_SNAKE_CASE__ : Any = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[str] = [ "encoder.version", "encoder.layers.*.norm_k.weight", "encoder.layers.*.norm_k.bias", "decoder.version", "decoder.layers.*.norm_k.weight", "decoder.layers.*.norm_k.bias", "decoder.pos_emb.pe_k", "speech_encoder_prenet.embed_positions._float_tensor", "text_decoder_prenet.embed_positions._float_tensor", ] SCREAMING_SNAKE_CASE__ : Any = IGNORE_KEYS + [ "encoder.proj", "text_encoder_prenet.*", "speech_decoder_prenet.*", "speech_decoder_postnet.*", ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = IGNORE_KEYS + [ "encoder.proj", "speech_encoder_prenet.*", "text_decoder_prenet.*", "text_decoder_postnet.*", ] SCREAMING_SNAKE_CASE__ : int = IGNORE_KEYS + [ "encoder.proj", "text_encoder_prenet.*", "text_decoder_prenet.*", "text_decoder_postnet.*", ] def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : List[Any] , lowercase__ : Union[str, Any] ) -> str: '''simple docstring''' for attribute in key.split('.' ): SCREAMING_SNAKE_CASE__ : Tuple = getattr(lowercase__ , lowercase__ ) if weight_type is not None: SCREAMING_SNAKE_CASE__ : int = getattr(lowercase__ , lowercase__ ).shape else: SCREAMING_SNAKE_CASE__ : List[str] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE__ : int = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "bias": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE__ : Union[str, Any] = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE__ : Optional[int] = value else: SCREAMING_SNAKE_CASE__ : Tuple = value logger.info(f'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' ) def _a ( lowercase__ : List[Any] , lowercase__ : Tuple ) -> Union[str, Any]: '''simple docstring''' for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE__ : int = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _a ( lowercase__ : Optional[int] , lowercase__ : Union[str, Any] , lowercase__ : Dict ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = [] if task == "s2t": SCREAMING_SNAKE_CASE__ : str = hf_model.speechta.encoder.prenet.feature_encoder SCREAMING_SNAKE_CASE__ : Tuple = MAPPING_S2T SCREAMING_SNAKE_CASE__ : List[Any] = IGNORE_KEYS_S2T elif task == "t2s": SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[Any] = MAPPING_T2S SCREAMING_SNAKE_CASE__ : int = IGNORE_KEYS_T2S elif task == "s2s": SCREAMING_SNAKE_CASE__ : Any = hf_model.speechta.encoder.prenet.feature_encoder SCREAMING_SNAKE_CASE__ : str = MAPPING_S2S SCREAMING_SNAKE_CASE__ : List[Any] = IGNORE_KEYS_S2S else: raise ValueError(f'''Unsupported task: {task}''' ) for name, value in fairseq_dict.items(): if should_ignore(lowercase__ , lowercase__ ): logger.info(f'''{name} was ignored''' ) continue SCREAMING_SNAKE_CASE__ : Optional[int] = False if "conv_layers" in name: load_conv_layer( lowercase__ , lowercase__ , lowercase__ , lowercase__ , hf_model.config.feat_extract_norm == 'group' , ) SCREAMING_SNAKE_CASE__ : List[Any] = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] = key.split('.*.' ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE__ : Any = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: SCREAMING_SNAKE_CASE__ : Dict = True if "*" in mapped_key: SCREAMING_SNAKE_CASE__ : Dict = name.split(lowercase__ )[0].split('.' )[-2] SCREAMING_SNAKE_CASE__ : int = mapped_key.replace('*' , lowercase__ ) if "weight_g" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE__ : int = 'weight_v' elif "bias" in name: SCREAMING_SNAKE_CASE__ : str = 'bias' elif "weight" in name: SCREAMING_SNAKE_CASE__ : List[str] = 'weight' elif "running_mean" in name: SCREAMING_SNAKE_CASE__ : Dict = 'running_mean' elif "running_var" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'running_var' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE__ : Any = 'num_batches_tracked' else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) continue if not is_used: unused_weights.append(lowercase__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Any , lowercase__ : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = full_name.split('conv_layers.' )[-1] SCREAMING_SNAKE_CASE__ : Optional[int] = name.split('.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(items[0] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Any = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : int = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Dict = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase__ ) @torch.no_grad() def _a ( lowercase__ : List[str] , lowercase__ : Optional[int] , lowercase__ : Optional[int] , lowercase__ : List[Any]=None , lowercase__ : Optional[Any]=None , lowercase__ : Any=None , ) -> str: '''simple docstring''' if config_path is not None: SCREAMING_SNAKE_CASE__ : int = SpeechTaConfig.from_pretrained(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = SpeechTaConfig() if task == "s2t": SCREAMING_SNAKE_CASE__ : str = config.max_text_positions SCREAMING_SNAKE_CASE__ : Optional[int] = SpeechTaForSpeechToText(lowercase__ ) elif task == "t2s": SCREAMING_SNAKE_CASE__ : Tuple = 18_76 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 6_00 SCREAMING_SNAKE_CASE__ : int = config.max_speech_positions SCREAMING_SNAKE_CASE__ : List[str] = SpeechTaForTextToSpeech(lowercase__ ) elif task == "s2s": SCREAMING_SNAKE_CASE__ : Any = 18_76 SCREAMING_SNAKE_CASE__ : Dict = config.max_speech_positions SCREAMING_SNAKE_CASE__ : List[Any] = SpeechTaForSpeechToSpeech(lowercase__ ) else: raise ValueError(f'''Unknown task name: {task}''' ) if vocab_path: SCREAMING_SNAKE_CASE__ : Dict = SpeechTaTokenizer(lowercase__ , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Union[str, Any] = AddedToken('<mask>' , lstrip=lowercase__ , rstrip=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = mask_token tokenizer.add_special_tokens({'mask_token': mask_token} ) tokenizer.add_tokens(['<ctc_blank>'] ) SCREAMING_SNAKE_CASE__ : List[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : Tuple = SpeechTaProcessor(tokenizer=lowercase__ , feature_extractor=lowercase__ ) processor.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = torch.load(lowercase__ ) recursively_load_weights(fairseq_checkpoint['model'] , lowercase__ , lowercase__ ) model.save_pretrained(lowercase__ ) if repo_id: print('Pushing to the hub...' ) processor.push_to_hub(lowercase__ ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--task", default="s2t", type=str, help="Type of the SpeechT5 model you'd like to convert. Should be one of 's2t', 't2s', 's2s'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--vocab_path", default=None, type=str, help="Path to SentencePiece model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
701
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class snake_case : def __init__( self : List[str] , a_ : Tuple , a_ : Any=13 , a_ : Any=7 , a_ : int=True , a_ : Tuple=True , a_ : Dict=True , a_ : str=True , a_ : str=99 , a_ : Tuple=32 , a_ : Dict=2 , a_ : Tuple=4 , a_ : List[Any]=37 , a_ : Optional[Any]="gelu" , a_ : Union[str, Any]=0.1 , a_ : Optional[Any]=0.1 , a_ : int=512 , a_ : List[Any]=16 , a_ : Tuple=2 , a_ : Union[str, Any]=0.02 , a_ : Union[str, Any]=False , a_ : List[str]=True , a_ : str="None" , a_ : Union[str, Any]=3 , a_ : List[Any]=4 , a_ : List[str]=None , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : Tuple = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : int = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices SCREAMING_SNAKE_CASE__ : Any = relative_attention SCREAMING_SNAKE_CASE__ : List[str] = position_biased_input SCREAMING_SNAKE_CASE__ : List[str] = pos_att_type SCREAMING_SNAKE_CASE__ : Optional[int] = scope def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=a_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Any , a_ : Union[str, Any] , a_ : List[Any] , a_ : Dict , a_ : str , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDebertaVaModel(config=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Optional[int] = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ : Any = model(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : int , a_ : Optional[Any] , a_ : int , a_ : Dict , a_ : int , a_ : str , a_ : Any , a_ : Any )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFDebertaVaForMaskedLM(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : int , a_ : Optional[Any] , a_ : int , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Tuple , a_ : str , a_ : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : List[Any] = TFDebertaVaForSequenceClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : int , a_ : Any , a_ : Optional[int] , a_ : Any , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDebertaVaForTokenClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Any = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Dict , a_ : Tuple , a_ : int , a_ : int , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaForQuestionAnswering(config=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) lowercase_ = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(a_ ) @require_tf class snake_case ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __lowercase( self : str )-> List[str]: """simple docstring""" pass @slow def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) SCREAMING_SNAKE_CASE__ : Dict = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) SCREAMING_SNAKE_CASE__ : List[str] = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , a_ , atol=1e-4 )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
class snake_case : def __init__( self : Tuple , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = size SCREAMING_SNAKE_CASE__ : Dict = [0] * size SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * size @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return index | (index + 1) @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return (index & (index + 1)) - 1 def __lowercase( self : List[str] , a_ : int , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = value while index < self.size: SCREAMING_SNAKE_CASE__ : Tuple = self.get_prev(a_ ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : str = value else: SCREAMING_SNAKE_CASE__ : Any = max(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_next(a_ ) def __lowercase( self : int , a_ : int , a_ : int )-> int: """simple docstring""" right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : Dict = 0 while left <= right: SCREAMING_SNAKE_CASE__ : Tuple = self.get_prev(a_ ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[str] = max(a_ , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Optional[int] = current_left else: SCREAMING_SNAKE_CASE__ : Any = max(a_ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''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))
636
0
import baseaa def _a ( lowercase__ : str ): '''simple docstring''' return baseaa.baaencode(string.encode('utf-8' ) ) def _a ( lowercase__ : bytes ): '''simple docstring''' return baseaa.baadecode(lowercase__ ).decode('utf-8' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Dict = "Hello World!" SCREAMING_SNAKE_CASE__ : Optional[int] = baseaa_encode(test) print(encoded) SCREAMING_SNAKE_CASE__ : Union[str, Any] = baseaa_decode(encoded) print(decoded)
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
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 SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json", } # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = [ 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, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 1_0563, 1_0786, 1_1420, 1_1709, 1_1907, 1_3163, 1_3697, 1_3700, 1_4808, 1_5306, 1_6410, 1_6791, 1_7992, 1_9203, 1_9510, 2_0724, 2_2305, 2_2935, 2_7007, 3_0109, 3_0420, 3_3409, 3_4949, 4_0283, 4_0493, 4_0549, 4_7282, 4_9146, 5_0257, 5_0359, 5_0360, 5_0361 ] SCREAMING_SNAKE_CASE__ : int = [ 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, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 1_0428, 1_0929, 1_1938, 1_2033, 1_2331, 1_2562, 1_3793, 1_4157, 1_4635, 1_5265, 1_5618, 1_6553, 1_6604, 1_8362, 1_8956, 2_0075, 2_1675, 2_2520, 2_6130, 2_6161, 2_6435, 2_8279, 2_9464, 3_1650, 3_2302, 3_2470, 3_6865, 4_2863, 4_7425, 4_9870, 5_0254, 5_0258, 5_0360, 5_0361, 5_0362 ] class snake_case ( UpperCamelCase_ ): lowercase_ = 'whisper' lowercase_ = ['past_key_values'] lowercase_ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : int , a_ : int=5_1865 , a_ : Optional[int]=80 , a_ : Tuple=6 , a_ : Optional[Any]=4 , a_ : int=6 , a_ : int=4 , a_ : Tuple=1536 , a_ : Tuple=1536 , a_ : str=0.0 , a_ : int=0.0 , a_ : List[Any]=5_0257 , a_ : Any=True , a_ : str=True , a_ : Union[str, Any]="gelu" , a_ : Tuple=256 , a_ : Any=0.0 , a_ : str=0.0 , a_ : int=0.0 , a_ : List[str]=0.02 , a_ : str=False , a_ : List[str]=1500 , a_ : Tuple=448 , a_ : str=5_0256 , a_ : str=5_0256 , a_ : Dict=5_0256 , a_ : Optional[int]=None , a_ : List[Any]=[220, 5_0256] , a_ : List[Any]=False , a_ : Tuple=256 , a_ : Tuple=False , a_ : str=0.05 , a_ : int=10 , a_ : Union[str, Any]=2 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=10 , a_ : int=0 , a_ : Any=7 , **a_ : List[Any] , )-> Optional[int]: """simple docstring""" __A : Any = vocab_size __A : int = num_mel_bins __A : Union[str, Any] = d_model __A : List[Any] = encoder_layers __A : Optional[int] = encoder_attention_heads __A : List[Any] = decoder_layers __A : Any = decoder_attention_heads __A : Tuple = decoder_ffn_dim __A : Any = encoder_ffn_dim __A : Optional[Any] = dropout __A : List[Any] = attention_dropout __A : Tuple = activation_dropout __A : List[Any] = activation_function __A : Optional[int] = init_std __A : Optional[Any] = encoder_layerdrop __A : Any = decoder_layerdrop __A : Tuple = use_cache __A : Union[str, Any] = encoder_layers __A : Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True __A : Any = max_source_positions __A : Any = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. __A : Any = classifier_proj_size __A : str = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __A : Any = apply_spec_augment __A : str = mask_time_prob __A : Optional[Any] = mask_time_length __A : Tuple = mask_time_min_masks __A : List[Any] = mask_feature_prob __A : int = mask_feature_length __A : int = mask_feature_min_masks __A : List[Any] = 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 snake_case ( UpperCamelCase_ ): @property def __lowercase( self : List[str] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" __A : Any = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ] ) if self.use_past: __A : Optional[int] = {0: 'batch'} else: __A : Optional[int] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(a_ , direction='inputs' ) return common_inputs def __lowercase( self : int , a_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional["TensorType"] = None , a_ : int = 2_2050 , a_ : float = 5.0 , a_ : int = 220 , )-> Mapping[str, Any]: """simple docstring""" __A : Optional[Any] = OrderedDict() __A : int = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=a_ , framework=a_ , sampling_rate=a_ , time_duration=a_ , frequency=a_ , ) __A : str = encoder_inputs['input_features'].shape[2] __A : Any = encoder_sequence_length // 2 if self.use_past else seq_length __A : Union[str, Any] = super().generate_dummy_inputs( preprocessor.tokenizer , a_ , a_ , a_ , a_ ) __A : Optional[Any] = encoder_inputs.pop('input_features' ) __A : Tuple = decoder_inputs.pop('decoder_input_ids' ) if "past_key_values" in decoder_inputs: __A : Any = decoder_inputs.pop('past_key_values' ) return dummy_inputs @property def __lowercase( self : int )-> float: """simple docstring""" return 1e-3
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( 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 , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def __lowercase( self : int , a_ : Any=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.random.RandomState(a_ ) SCREAMING_SNAKE_CASE__ : int = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : str = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : int = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE__ : int = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE__ : List[str] = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE__ : Any = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : Dict )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE__ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : int = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : Tuple = 3 * [inputs['prompt']] # forward SCREAMING_SNAKE_CASE__ : Optional[int] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = 3 * [inputs.pop('prompt' )] SCREAMING_SNAKE_CASE__ : List[Any] = pipe.tokenizer( a_ , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors='np' , ) SCREAMING_SNAKE_CASE__ : Any = text_inputs['input_ids'] SCREAMING_SNAKE_CASE__ : int = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = prompt_embeds # forward SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = 3 * ['this is a negative prompt'] SCREAMING_SNAKE_CASE__ : Dict = negative_prompt SCREAMING_SNAKE_CASE__ : Dict = 3 * [inputs['prompt']] # forward SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.images[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = self.get_dummy_inputs() SCREAMING_SNAKE_CASE__ : int = 3 * [inputs.pop('prompt' )] SCREAMING_SNAKE_CASE__ : Dict = [] for p in [prompt, negative_prompt]: SCREAMING_SNAKE_CASE__ : Dict = pipe.tokenizer( a_ , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors='np' , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = text_inputs['input_ids'] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) SCREAMING_SNAKE_CASE__ : Any = embeds # forward SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : int = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class snake_case ( unittest.TestCase ): @property def __lowercase( self : Tuple )-> Tuple: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ort.SessionOptions() SCREAMING_SNAKE_CASE__ : int = False return options def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'A painting of a squirrel eating a burger' np.random.seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Any = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DDIMScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) SCREAMING_SNAKE_CASE__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = 'open neural network exchange' SCREAMING_SNAKE_CASE__ : List[str] = np.random.RandomState(0 ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type='np' ) SCREAMING_SNAKE_CASE__ : Any = output.images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) SCREAMING_SNAKE_CASE__ : str = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 'open neural network exchange' SCREAMING_SNAKE_CASE__ : str = np.random.RandomState(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type='np' ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 def test_callback_fn(a_ : int , a_ : int , a_ : np.ndarray ) -> None: SCREAMING_SNAKE_CASE__ : Any = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Optional[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = np.array( [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = np.array( [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 'Andromeda galaxy in a bottle' SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.random.RandomState(0 ) pipe( prompt=a_ , num_inference_steps=5 , guidance_scale=7.5 , generator=a_ , callback=a_ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(a_ , a_ ) assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ : Any = pipe('example prompt' , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(a_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ : Dict = pipe('example prompt' , num_inference_steps=2 ).images[0] assert image is not None
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json", "uclanlp/visualbert-vqa-pre": "https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json", "uclanlp/visualbert-vqa-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json" ), "uclanlp/visualbert-vcr": "https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json", "uclanlp/visualbert-vcr-pre": "https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json", "uclanlp/visualbert-vcr-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json" ), "uclanlp/visualbert-nlvr2": "https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json", "uclanlp/visualbert-nlvr2-pre": "https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json", "uclanlp/visualbert-nlvr2-coco-pre": ( "https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json" ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class snake_case ( UpperCamelCase_ ): lowercase_ = 'visual_bert' def __init__( self : Tuple , a_ : Optional[Any]=3_0522 , a_ : Any=768 , a_ : Tuple=512 , a_ : Any=12 , a_ : str=12 , a_ : Optional[int]=3072 , a_ : List[Any]="gelu" , a_ : Any=0.1 , a_ : int=0.1 , a_ : Any=512 , a_ : Union[str, Any]=2 , a_ : Union[str, Any]=0.02 , a_ : int=1e-1_2 , a_ : Optional[int]=False , a_ : Tuple=True , a_ : Optional[Any]=1 , a_ : List[str]=0 , a_ : Optional[int]=2 , **a_ : List[Any] , )-> Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = visual_embedding_dim SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = bypass_transformer SCREAMING_SNAKE_CASE__ : List[str] = special_visual_initialize
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : Optional[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : List[str] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : str = do_rescale SCREAMING_SNAKE_CASE__ : Any = rescale_factor SCREAMING_SNAKE_CASE__ : List[Any] = do_pad SCREAMING_SNAKE_CASE__ : int = pad_size def __lowercase( self : List[Any] , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Tuple )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[str] , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : int = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : List[str] , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Any , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : Tuple = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[Any] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Optional[int] = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None SCREAMING_SNAKE_CASE__ : Dict = "<" if sys.byteorder == "little" else ">" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image SCREAMING_SNAKE_CASE__ : Dict = [ np.dtype("|b1"), np.dtype("|u1"), np.dtype("<u2"), np.dtype(">u2"), np.dtype("<i2"), np.dtype(">i2"), np.dtype("<u4"), np.dtype(">u4"), np.dtype("<i4"), np.dtype(">i4"), np.dtype("<f4"), np.dtype(">f4"), np.dtype("<f8"), np.dtype(">f8"), ] @dataclass class snake_case : lowercase_ = True lowercase_ = None # Automatically constructed lowercase_ = 'PIL.Image.Image' lowercase_ = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowercase_ = field(default='Image' , init=UpperCamelCase_ , repr=UpperCamelCase_ ) def __call__( self : Optional[int] )-> List[str]: """simple docstring""" return self.pa_type def __lowercase( self : Tuple , a_ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] )-> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Any = np.array(a_ ) if isinstance(a_ , a_ ): return {"path": value, "bytes": None} elif isinstance(a_ , a_ ): return {"path": None, "bytes": value} elif isinstance(a_ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(a_ ) elif isinstance(a_ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(a_ ) elif value.get('path' ) is not None and os.path.isfile(value['path'] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get('path' )} elif value.get('bytes' ) is not None or value.get('path' ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('bytes' ), "path": value.get('path' )} else: raise ValueError( F'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __lowercase( self : str , a_ : dict , a_ : Dict=None )-> "PIL.Image.Image": """simple docstring""" if not self.decode: raise RuntimeError('Decoding is disabled for this feature. Please use Image(decode=True) instead.' ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support decoding images, please install \'Pillow\'.' ) if token_per_repo_id is None: SCREAMING_SNAKE_CASE__ : Any = {} SCREAMING_SNAKE_CASE__ : Tuple = value['path'], value['bytes'] if bytes_ is None: if path is None: raise ValueError(F'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(a_ ): SCREAMING_SNAKE_CASE__ : List[Any] = PIL.Image.open(a_ ) else: SCREAMING_SNAKE_CASE__ : int = path.split('::' )[-1] try: SCREAMING_SNAKE_CASE__ : Optional[Any] = string_to_dict(a_ , config.HUB_DATASETS_URL )['repo_id'] SCREAMING_SNAKE_CASE__ : int = token_per_repo_id.get(a_ ) except ValueError: SCREAMING_SNAKE_CASE__ : str = None with xopen(a_ , 'rb' , use_auth_token=a_ ) as f: SCREAMING_SNAKE_CASE__ : Optional[int] = BytesIO(f.read() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = PIL.Image.open(bytes_ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowercase( self : Tuple )-> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def __lowercase( self : Optional[int] , a_ : Union[pa.StringArray, pa.StructArray, pa.ListArray] )-> pa.StructArray: """simple docstring""" if pa.types.is_string(storage.type ): SCREAMING_SNAKE_CASE__ : Tuple = pa.array([None] * len(a_ ) , type=pa.binary() ) SCREAMING_SNAKE_CASE__ : Any = pa.StructArray.from_arrays([bytes_array, storage] , ['bytes', 'path'] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array([None] * len(a_ ) , type=pa.string() ) SCREAMING_SNAKE_CASE__ : List[Any] = pa.StructArray.from_arrays([storage, path_array] , ['bytes', 'path'] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('bytes' ) >= 0: SCREAMING_SNAKE_CASE__ : List[Any] = storage.field('bytes' ) else: SCREAMING_SNAKE_CASE__ : Any = pa.array([None] * len(a_ ) , type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: SCREAMING_SNAKE_CASE__ : Optional[int] = storage.field('path' ) else: SCREAMING_SNAKE_CASE__ : int = pa.array([None] * len(a_ ) , type=pa.string() ) SCREAMING_SNAKE_CASE__ : Optional[int] = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): SCREAMING_SNAKE_CASE__ : Optional[int] = pa.array( [encode_np_array(np.array(a_ ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array([None] * len(a_ ) , type=pa.string() ) SCREAMING_SNAKE_CASE__ : Any = pa.StructArray.from_arrays( [bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null() ) return array_cast(a_ , self.pa_type ) def __lowercase( self : Any , a_ : pa.StructArray )-> pa.StructArray: """simple docstring""" @no_op_if_value_is_null def path_to_bytes(a_ : Any ): with xopen(a_ , 'rb' ) as f: SCREAMING_SNAKE_CASE__ : Tuple = f.read() return bytes_ SCREAMING_SNAKE_CASE__ : Union[str, Any] = pa.array( [ (path_to_bytes(x['path'] ) if x['bytes'] is None else x['bytes']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) SCREAMING_SNAKE_CASE__ : List[Any] = pa.array( [os.path.basename(a_ ) if path is not None else None for path in storage.field('path' ).to_pylist()] , type=pa.string() , ) SCREAMING_SNAKE_CASE__ : List[str] = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null() ) return array_cast(a_ , self.pa_type ) def _a ( ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() SCREAMING_SNAKE_CASE__ : Any = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _a ( lowercase__ : "PIL.Image.Image" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = BytesIO() if image.format in list_image_compression_formats(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = image.format else: SCREAMING_SNAKE_CASE__ : str = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(lowercase__ , format=lowercase__ ) return buffer.getvalue() def _a ( lowercase__ : "PIL.Image.Image" ): '''simple docstring''' if hasattr(lowercase__ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase__ )} def _a ( lowercase__ : np.ndarray ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) SCREAMING_SNAKE_CASE__ : str = array.dtype SCREAMING_SNAKE_CASE__ : List[Any] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER SCREAMING_SNAKE_CASE__ : Union[str, Any] = dtype.kind SCREAMING_SNAKE_CASE__ : List[str] = dtype.itemsize SCREAMING_SNAKE_CASE__ : Optional[int] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: SCREAMING_SNAKE_CASE__ : Optional[Any] = np.dtype('|u1' ) if dtype_kind not in ["u", "i"]: raise TypeError( f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: SCREAMING_SNAKE_CASE__ : Tuple = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = dtype_byteorder + dtype_kind + str(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dtype(lowercase__ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) SCREAMING_SNAKE_CASE__ : List[str] = PIL.Image.fromarray(array.astype(lowercase__ ) ) return {"path": None, "bytes": image_to_bytes(lowercase__ )} def _a ( lowercase__ : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: SCREAMING_SNAKE_CASE__ : Optional[Any] = first_non_null_value(lowercase__ ) if isinstance(lowercase__ , lowercase__ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase__ , np.ndarray ): SCREAMING_SNAKE_CASE__ : List[Any] = no_op_if_value_is_null(lowercase__ ) return [obj_to_image_dict_func(lowercase__ ) for obj in objs] elif isinstance(lowercase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ : List[Any] = no_op_if_value_is_null(lowercase__ ) return [obj_to_image_dict_func(lowercase__ ) for obj in objs] else: return objs else: return objs
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=UpperCamelCase_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = field(default='audio-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) lowercase_ = Features({'audio': Audio()} ) lowercase_ = Features({'labels': ClassLabel} ) lowercase_ = 'audio' lowercase_ = 'labels' def __lowercase( self : Tuple , a_ : Optional[int] )-> List[str]: """simple docstring""" if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , a_ ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ : List[Any] = self.label_schema.copy() SCREAMING_SNAKE_CASE__ : Any = features[self.label_column] SCREAMING_SNAKE_CASE__ : List[Any] = label_schema return task_template @property def __lowercase( self : Tuple )-> Dict[str, str]: """simple docstring""" return { self.audio_column: "audio", self.label_column: "labels", }
711
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import math def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowercase__ ) def _a ( lowercase__ : float = 1 / 1_23_45 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 while True: SCREAMING_SNAKE_CASE__ : List[str] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowercase__ ): SCREAMING_SNAKE_CASE__ : str = int(lowercase__ ) total_partitions += 1 if check_partition_perfect(lowercase__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowercase__ ) integer += 1 if __name__ == "__main__": print(F"""{solution() = }""")
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) # TODO Update this SCREAMING_SNAKE_CASE__ : Tuple = { "facebook/esm-1b": "https://huggingface.co/facebook/esm-1b/resolve/main/config.json", # See all ESM models at https://huggingface.co/models?filter=esm } class snake_case ( UpperCamelCase_ ): lowercase_ = 'esm' def __init__( self : int , a_ : Dict=None , a_ : Any=None , a_ : List[Any]=None , a_ : Dict=768 , a_ : int=12 , a_ : Optional[Any]=12 , a_ : Tuple=3072 , a_ : Dict=0.1 , a_ : Any=0.1 , a_ : List[str]=1026 , a_ : List[Any]=0.02 , a_ : Optional[Any]=1e-1_2 , a_ : int="absolute" , a_ : List[str]=True , a_ : List[Any]=None , a_ : str=False , a_ : Any=False , a_ : List[str]=None , a_ : str=None , **a_ : List[str] , )-> List[str]: """simple docstring""" super().__init__(pad_token_id=a_ , mask_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = position_embedding_type SCREAMING_SNAKE_CASE__ : Dict = use_cache SCREAMING_SNAKE_CASE__ : List[str] = emb_layer_norm_before SCREAMING_SNAKE_CASE__ : Union[str, Any] = token_dropout SCREAMING_SNAKE_CASE__ : Dict = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('No esmfold_config supplied for folding model, using default values.' ) SCREAMING_SNAKE_CASE__ : List[Any] = EsmFoldConfig() elif isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = EsmFoldConfig(**a_ ) SCREAMING_SNAKE_CASE__ : Any = esmfold_config if vocab_list is None: logger.warning('No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!' ) SCREAMING_SNAKE_CASE__ : int = get_default_vocab_list() else: SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_list else: SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[Any] = None if self.esmfold_config is not None and getattr(self.esmfold_config , 'use_esm_attn_map' , a_ ): raise ValueError('The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!' ) def __lowercase( self : Union[str, Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = super().to_dict() if isinstance(self.esmfold_config , a_ ): SCREAMING_SNAKE_CASE__ : int = self.esmfold_config.to_dict() return output @dataclass class snake_case : lowercase_ = None lowercase_ = True lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = 0 lowercase_ = True lowercase_ = False lowercase_ = 128 lowercase_ = None def __lowercase( self : List[str] )-> Dict: """simple docstring""" if self.trunk is None: SCREAMING_SNAKE_CASE__ : str = TrunkConfig() elif isinstance(self.trunk , a_ ): SCREAMING_SNAKE_CASE__ : Dict = TrunkConfig(**self.trunk ) def __lowercase( self : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = asdict(self ) SCREAMING_SNAKE_CASE__ : List[str] = self.trunk.to_dict() return output @dataclass class snake_case : lowercase_ = 48 lowercase_ = 1_024 lowercase_ = 128 lowercase_ = 32 lowercase_ = 32 lowercase_ = 32 lowercase_ = 0 lowercase_ = 0 lowercase_ = False lowercase_ = 4 lowercase_ = 128 lowercase_ = None def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" if self.structure_module is None: SCREAMING_SNAKE_CASE__ : Dict = StructureModuleConfig() elif isinstance(self.structure_module , a_ ): SCREAMING_SNAKE_CASE__ : Dict = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F'''`max_recycles` should be positive, got {self.max_recycles}.''' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got' F''' {self.sequence_state_dim} and {self.sequence_state_dim}.''' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got' F''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.''' ) SCREAMING_SNAKE_CASE__ : int = self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE__ : Optional[int] = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got' F''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.''' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got' F''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.''' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.''' ) if self.dropout >= 0.4: raise ValueError(F'''`dropout` should not be greater than 0.4, got {self.dropout}.''' ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = asdict(self ) SCREAMING_SNAKE_CASE__ : List[str] = self.structure_module.to_dict() return output @dataclass class snake_case : lowercase_ = 384 lowercase_ = 128 lowercase_ = 16 lowercase_ = 128 lowercase_ = 12 lowercase_ = 4 lowercase_ = 8 lowercase_ = 0.1 lowercase_ = 8 lowercase_ = 1 lowercase_ = 2 lowercase_ = 7 lowercase_ = 10 lowercase_ = 1e-8 lowercase_ = 1e5 def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return asdict(self ) def _a ( ): '''simple docstring''' return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name SCREAMING_SNAKE_CASE__ : str = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def _a ( lowercase__ : Dict , lowercase__ : Union[str, Any] , lowercase__ : int=8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE__ : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _a ( lowercase__ : str , lowercase__ : List[str]=5_12 , lowercase__ : Dict=5_12 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) SCREAMING_SNAKE_CASE__ : Tuple = np.array(pil_image.convert('RGB' ) ) SCREAMING_SNAKE_CASE__ : Dict = arr.astype(np.floataa ) / 127.5 - 1 SCREAMING_SNAKE_CASE__ : str = np.transpose(lowercase__ , [2, 0, 1] ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.from_numpy(lowercase__ ).unsqueeze(0 ) return image class snake_case ( UpperCamelCase_ ): def __init__( self : Dict , a_ : UNetaDConditionModel , a_ : DDPMScheduler , a_ : VQModel , )-> List[Any]: """simple docstring""" super().__init__() self.register_modules( unet=a_ , scheduler=a_ , movq=a_ , ) SCREAMING_SNAKE_CASE__ : Any = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowercase( self : Tuple , a_ : List[Any] , a_ : int , a_ : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = min(int(num_inference_steps * strength ) , a_ ) SCREAMING_SNAKE_CASE__ : Dict = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE__ : Dict = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowercase( self : Dict , a_ : Any , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : List[str] , a_ : int , a_ : List[Any]=None )-> List[str]: """simple docstring""" if not isinstance(a_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a_ )}''' ) SCREAMING_SNAKE_CASE__ : Dict = image.to(device=a_ , dtype=a_ ) SCREAMING_SNAKE_CASE__ : Dict = batch_size * num_images_per_prompt if image.shape[1] == 4: SCREAMING_SNAKE_CASE__ : Optional[int] = image else: if isinstance(a_ , a_ ) and len(a_ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(a_ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a_ ) ] SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat(a_ , dim=0 ) else: SCREAMING_SNAKE_CASE__ : str = self.movq.encode(a_ ).latent_dist.sample(a_ ) SCREAMING_SNAKE_CASE__ : int = self.movq.config.scaling_factor * init_latents SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([init_latents] , dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = init_latents.shape SCREAMING_SNAKE_CASE__ : str = randn_tensor(a_ , generator=a_ , device=a_ , dtype=a_ ) # get latents SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler.add_noise(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = init_latents return latents def __lowercase( self : Union[str, Any] , a_ : List[Any]=0 )-> Dict: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) SCREAMING_SNAKE_CASE__ : Any = torch.device(F'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE__ : List[str] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(a_ , a_ ) def __lowercase( self : List[Any] , a_ : Optional[int]=0 )-> List[str]: """simple docstring""" if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) SCREAMING_SNAKE_CASE__ : str = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=a_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE__ : Optional[int] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE__ : Dict = cpu_offload_with_hook(a_ , a_ , prev_module_hook=a_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE__ : Union[str, Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(a_ , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(a_ ) def __call__( self : Any , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : int = 512 , a_ : int = 512 , a_ : int = 100 , a_ : float = 4.0 , a_ : float = 0.3 , a_ : int = 1 , a_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a_ : Optional[str] = "pil" , a_ : bool = True , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._execution_device SCREAMING_SNAKE_CASE__ : Any = guidance_scale > 1.0 if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_embeds.shape[0] if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat(a_ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : Optional[int] = image_embeds.repeat_interleave(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = negative_image_embeds.repeat_interleave(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=a_ ) if not isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = [image] if not all(isinstance(a_ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'''Input is in incorrect format: {[type(a_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([prepare_image(a_ , a_ , a_ ) for i in image] , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = image.to(dtype=image_embeds.dtype , device=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.movq.encode(a_ )['latents'] SCREAMING_SNAKE_CASE__ : str = latents.repeat_interleave(a_ , dim=0 ) self.scheduler.set_timesteps(a_ , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_timesteps(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = timesteps[:1].repeat(batch_size * num_images_per_prompt ) SCREAMING_SNAKE_CASE__ : Tuple = downscale_height_and_width(a_ , a_ , self.movq_scale_factor ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_latents( a_ , a_ , a_ , a_ , image_embeds.dtype , a_ , a_ ) for i, t in enumerate(self.progress_bar(a_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'image_embeds': image_embeds} SCREAMING_SNAKE_CASE__ : Tuple = self.unet( sample=a_ , timestep=a_ , encoder_hidden_states=a_ , added_cond_kwargs=a_ , return_dict=a_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE__ : int = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler.step( a_ , a_ , a_ , generator=a_ , )[0] # post-processing SCREAMING_SNAKE_CASE__ : List[str] = self.movq.decode(a_ , force_not_quantize=a_ )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE__ : Dict = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE__ : List[str] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : Optional[int] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCamelCase_ ) , 'Tatoeba directory does not exist.' ) class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = tempfile.mkdtemp() return TatoebaConverter(save_dir=a_ ) @slow def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" self.resolver.convert_models(['heb-eng'] ) @slow def __lowercase( self : Optional[int] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.resolver.write_model_card('opus-mt-he-en' , dry_run=a_ ) assert mmeta["long_pair"] == "heb-eng"
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class snake_case ( UpperCamelCase_ ): @staticmethod @abstractmethod def __lowercase( a_ : ArgumentParser )-> Optional[Any]: """simple docstring""" raise NotImplementedError() @abstractmethod def __lowercase( self : int )-> Optional[int]: """simple docstring""" raise NotImplementedError()
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = field(default='image-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) lowercase_ = Features({'image': Image()} ) lowercase_ = Features({'labels': ClassLabel} ) lowercase_ = 'image' lowercase_ = 'labels' def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , a_ ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.label_schema.copy() SCREAMING_SNAKE_CASE__ : Optional[int] = features[self.label_column] SCREAMING_SNAKE_CASE__ : List[Any] = label_schema return task_template @property def __lowercase( self : Tuple )-> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = 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_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" 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 __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if isinstance(lowercase__ , collections.abc.Iterable ): return x return (x, x) @require_flax class snake_case : def __lowercase( self : Union[str, Any] , a_ : Optional[Any] , a_ : str )-> Tuple: """simple docstring""" pass def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" pass def __lowercase( self : str )-> Tuple: """simple docstring""" pass def __lowercase( self : int , a_ : np.ndarray , a_ : np.ndarray , a_ : float )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.abs((a - b) ).max() self.assertLessEqual(a_ , a_ , F'''Difference between torch and flax is {diff} (>= {tol}).''' ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Any , a_ : str=None , **a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : str = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowercase( self : Any , a_ : Any , a_ : str , a_ : Union[str, Any] , a_ : List[str] , a_ : Optional[Any]=None , **a_ : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : Any , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any=None , **a_ : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = after_output[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-3 ) def __lowercase( self : List[Any] , a_ : int , a_ : Dict , a_ : str , a_ : Tuple , a_ : Any=None , **a_ : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : int = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : int = model( input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ ) SCREAMING_SNAKE_CASE__ : str = output.vision_model_output.attentions self.assertEqual(len(a_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : int = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE__ : List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE__ : Dict = output.text_model_output.attentions self.assertEqual(len(a_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowercase( self : List[Any] , a_ : Tuple , a_ : List[Any] , a_ : Optional[int] )-> Tuple: """simple docstring""" pt_model.to(a_ ) pt_model.eval() # prepare inputs SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict SCREAMING_SNAKE_CASE__ : str = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = pt_model(**a_ ).to_tuple() SCREAMING_SNAKE_CASE__ : Optional[int] = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = FlaxVisionTextDualEncoderModel.from_pretrained(a_ , from_pt=a_ ) SCREAMING_SNAKE_CASE__ : str = fx_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = VisionTextDualEncoderModel.from_pretrained(a_ , from_flax=a_ ) pt_model_loaded.to(a_ ) pt_model_loaded.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = pt_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(a_ , pt_output_loaded.numpy() , 4e-2 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int , a_ : Dict )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : str = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ ) SCREAMING_SNAKE_CASE__ : str = fx_state self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : str , a_ : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = load_flax_weights_in_pytorch_model(a_ , fx_model.params ) self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**a_ ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**a_ ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() self.check_save_load(**a_ ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**a_ ) @is_pt_flax_cross_test def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = config_inputs_dict.pop('vision_config' ) SCREAMING_SNAKE_CASE__ : List[str] = config_inputs_dict.pop('text_config' ) SCREAMING_SNAKE_CASE__ : List[Any] = config_inputs_dict self.check_equivalence_pt_to_flax(a_ , a_ , a_ ) self.check_equivalence_flax_to_pt(a_ , a_ , a_ ) @slow def __lowercase( self : Union[str, Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_pretrained_model_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : Tuple = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = after_outputs[0] SCREAMING_SNAKE_CASE__ : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-5 ) @require_flax class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = 13 SCREAMING_SNAKE_CASE__ : Dict = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : List[str] , a_ : Optional[Any] , a_ : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FlaxViTModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxViTModelTester(self ) SCREAMING_SNAKE_CASE__ : int = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[str] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Any = vision_config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = 13 SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : int = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : Union[str, Any] , a_ : Tuple , a_ : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FlaxCLIPVisionModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxCLIPVisionModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = clip_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) SCREAMING_SNAKE_CASE__ : Any = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) SCREAMING_SNAKE_CASE__ : Any = processor( text=['una foto di un gatto', 'una foto di un cane'] , images=a_ , padding=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : str = model(**a_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) SCREAMING_SNAKE_CASE__ : List[str] = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , a_ , atol=1e-3 ) )
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = '' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key SCREAMING_SNAKE_CASE__ : Any = remove_duplicates(key.upper() ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # First fill cipher with key characters SCREAMING_SNAKE_CASE__ : Union[str, Any] = {alphabet[i]: char for i, char in enumerate(lowercase__ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(lowercase__ ) , 26 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 SCREAMING_SNAKE_CASE__ : Any = alphabet[i - offset] SCREAMING_SNAKE_CASE__ : str = char return cipher_alphabet def _a ( lowercase__ : str , lowercase__ : dict[str, str] ): '''simple docstring''' return "".join(cipher_map.get(lowercase__ , lowercase__ ) for ch in message.upper() ) def _a ( lowercase__ : str , lowercase__ : dict[str, str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(lowercase__ , lowercase__ ) for ch in message.upper() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter message to encode or decode: ' ).strip() SCREAMING_SNAKE_CASE__ : Tuple = input('Enter keyword: ' ).strip() SCREAMING_SNAKE_CASE__ : List[Any] = input('Encipher or decipher? E/D:' ).strip()[0].lower() try: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'e': encipher, 'd': decipher}[option] except KeyError: raise KeyError('invalid input option' ) SCREAMING_SNAKE_CASE__ : List[Any] = create_cipher_map(lowercase__ ) print(func(lowercase__ , lowercase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
from math import ceil def _a ( lowercase__ : int , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = list(range(0 , lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check SCREAMING_SNAKE_CASE__ : Any = [] for i in device_map_blocks: if device_map_blocks.count(lowercase__ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(lowercase__ ) # Missing blocks SCREAMING_SNAKE_CASE__ : Union[str, Any] = [i for i in blocks if i not in device_map_blocks] SCREAMING_SNAKE_CASE__ : Any = [i for i in device_map_blocks if i not in blocks] if len(lowercase__ ) != 0: raise ValueError( 'Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.' ' These attention blocks were specified more than once: ' + str(lowercase__ ) ) if len(lowercase__ ) != 0: raise ValueError( 'There are attention blocks for this model that are not specified in the device_map. Add these attention ' 'blocks to a device on the device_map: ' + str(lowercase__ ) ) if len(lowercase__ ) != 0: raise ValueError( 'The device_map contains more attention blocks than this model has. Remove these from the device_map:' + str(lowercase__ ) ) def _a ( lowercase__ : str , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = list(range(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = int(ceil(n_layers / len(lowercase__ ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = [layers[i : i + n_blocks] for i in range(0 , lowercase__ , lowercase__ )] return dict(zip(lowercase__ , lowercase__ ) )
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) def _a ( lowercase__ : str , lowercase__ : int , lowercase__ : Any ): '''simple docstring''' return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def _a ( lowercase__ : np.ndarray , lowercase__ : Optional[str] , lowercase__ : Optional[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = to_pil_image(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = pil_image.size SCREAMING_SNAKE_CASE__ : Dict = pytesseract.image_to_data(lowercase__ , lang=lowercase__ , output_type='dict' , config=lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE__ : List[str] = [idx for idx, word in enumerate(lowercase__ ) if not word.strip()] SCREAMING_SNAKE_CASE__ : Any = [word for idx, word in enumerate(lowercase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : str = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : Optional[int] = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : List[str] = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE__ : List[str] = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE__ : Optional[int] = [] for x, y, w, h in zip(lowercase__ , lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = [x, y, x + w, y + h] actual_boxes.append(lowercase__ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE__ : List[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase__ , lowercase__ , lowercase__ ) ) assert len(lowercase__ ) == len(lowercase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Dict[str, int] = None , a_ : PILImageResampling = PILImageResampling.BILINEAR , a_ : bool = True , a_ : float = 1 / 255 , a_ : bool = True , a_ : Union[float, Iterable[float]] = None , a_ : Union[float, Iterable[float]] = None , a_ : bool = True , a_ : Optional[str] = None , a_ : Optional[str] = "" , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = size if size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE__ : List[Any] = get_size_dict(a_ ) SCREAMING_SNAKE_CASE__ : Dict = do_resize SCREAMING_SNAKE_CASE__ : Union[str, Any] = size SCREAMING_SNAKE_CASE__ : Tuple = resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE__ : str = rescale_value SCREAMING_SNAKE_CASE__ : str = do_normalize SCREAMING_SNAKE_CASE__ : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE__ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD SCREAMING_SNAKE_CASE__ : Dict = apply_ocr SCREAMING_SNAKE_CASE__ : Any = ocr_lang SCREAMING_SNAKE_CASE__ : Dict = tesseract_config def __lowercase( self : str , a_ : np.ndarray , a_ : Dict[str, int] , a_ : PILImageResampling = PILImageResampling.BILINEAR , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[str] , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = (size['height'], size['width']) return resize(a_ , size=a_ , resample=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[Any] , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : Union[float, Iterable[float]] , a_ : Union[float, Iterable[float]] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Tuple , )-> np.ndarray: """simple docstring""" return normalize(a_ , mean=a_ , std=a_ , data_format=a_ , **a_ ) def __lowercase( self : int , a_ : ImageInput , a_ : bool = None , a_ : Dict[str, int] = None , a_ : Union[str, Any]=None , a_ : bool = None , a_ : float = None , a_ : bool = None , a_ : Union[float, Iterable[float]] = None , a_ : Union[float, Iterable[float]] = None , a_ : bool = None , a_ : Optional[str] = None , a_ : Optional[str] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : ChannelDimension = ChannelDimension.FIRST , **a_ : List[str] , )-> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : str = get_size_dict(a_ ) SCREAMING_SNAKE_CASE__ : Dict = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : Any = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE__ : List[Any] = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE__ : List[Any] = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE__ : Optional[Any] = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_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('If do_normalize is True, image_mean and image_std must be specified.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Any = [to_numpy_array(a_ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , 'pytesseract' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for image in images: SCREAMING_SNAKE_CASE__ : Tuple = apply_tesseract(a_ , a_ , a_ ) words_batch.append(a_ ) boxes_batch.append(a_ ) if do_resize: SCREAMING_SNAKE_CASE__ : Tuple = [self.resize(image=a_ , size=a_ , resample=a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : List[str] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : str = [self.normalize(image=a_ , mean=a_ , std=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Dict = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Any = BatchFeature(data={'pixel_values': images} , tensor_type=a_ ) if apply_ocr: SCREAMING_SNAKE_CASE__ : Optional[int] = words_batch SCREAMING_SNAKE_CASE__ : Optional[Any] = boxes_batch return data
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer SCREAMING_SNAKE_CASE__ : Optional[Any] = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast SCREAMING_SNAKE_CASE__ : List[str] = TaTokenizerFast SCREAMING_SNAKE_CASE__ : Optional[int] = {"configuration_mt5": ["MT5Config", "MT5OnnxConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "MT5EncoderModel", "MT5ForConditionalGeneration", "MT5ForQuestionAnswering", "MT5Model", "MT5PreTrainedModel", "MT5Stack", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["TFMT5EncoderModel", "TFMT5ForConditionalGeneration", "TFMT5Model"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FlaxMT5EncoderModel", "FlaxMT5ForConditionalGeneration", "FlaxMT5Model"] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule( __name__, globals()["__file__"], _import_structure, extra_objects={"MT5Tokenizer": MTaTokenizer, "MT5TokenizerFast": MTaTokenizerFast}, module_spec=__spec__, )
700
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = mock.Mock() SCREAMING_SNAKE_CASE__ : int = 500 SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : List[Any] = HTTPError SCREAMING_SNAKE_CASE__ : List[str] = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=a_ ) as mock_head: SCREAMING_SNAKE_CASE__ : Tuple = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __lowercase( self : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = mock.Mock() SCREAMING_SNAKE_CASE__ : List[str] = 500 SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : List[str] = HTTPError SCREAMING_SNAKE_CASE__ : Optional[Any] = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ : List[str] = GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=a_ ) as mock_head: SCREAMING_SNAKE_CASE__ : Any = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE__ : str = tempfile.mktemp() with open(a_ , 'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = AlbertTokenizer.from_pretrained(a_ ) finally: os.remove(a_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' , 'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' , a_ ) SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class snake_case ( unittest.TestCase ): lowercase_ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def __lowercase( cls : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TOKEN HfFolder.save_token(a_ ) @classmethod def __lowercase( cls : Any )-> Dict: """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(a_ , 'vocab.txt' ) with open(a_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : Tuple = BertTokenizer(a_ ) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a_ , repo_id='test-tokenizer' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Dict = BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(a_ , 'vocab.txt' ) with open(a_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : Dict = BertTokenizer(a_ ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Optional[Any] = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a_ , repo_id='valid_org/test-tokenizer-org' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : int = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(a_ , 'vocab.txt' ) with open(a_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : int = CustomTokenizer(a_ ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(a_ , 'vocab.txt' ) with open(a_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : int = BertTokenizerFast.from_pretrained(a_ ) bert_tokenizer.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Any = CustomTokenizerFast.from_pretrained(a_ ) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained( F'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS]', ' This is a ', 'extra_id_100'] ) def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) , ['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) , ['BC', 'A'] ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) , ['AB', 'C'] ) def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) , ['ABC', 'D'] ) def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = Trie() SCREAMING_SNAKE_CASE__ : Optional[int] = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a_ , ['AB', 'C'] )
701
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = r'\w+[.]\d+' SCREAMING_SNAKE_CASE__ : Dict = re.findall(lowercase__ , lowercase__ ) for pat in pats: SCREAMING_SNAKE_CASE__ : int = key.replace(lowercase__ , '_'.join(pat.split('.' ) ) ) return key def _a ( lowercase__ : List[str] , lowercase__ : int , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = pt_tuple_key[:-1] + ('scale',) if ( any('norm' in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ('scale',) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: SCREAMING_SNAKE_CASE__ : List[Any] = pt_tuple_key[:-1] + ('scale',) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tuple_key[:-1] + ('embedding',) return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE__ : List[Any] = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight": SCREAMING_SNAKE_CASE__ : Dict = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tuple_key[:-1] + ('weight',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE__ : Dict = pt_tuple_key[:-1] + ('bias',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def _a ( lowercase__ : Tuple , lowercase__ : Tuple , lowercase__ : List[str]=42 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params SCREAMING_SNAKE_CASE__ : int = flax_model.init_weights(PRNGKey(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Any = flatten_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : Any = rename_key(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = tuple(renamed_pt_key.split('.' ) ) # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ : Dict = rename_key_and_reshape_tensor(lowercase__ , lowercase__ , lowercase__ ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : Dict = jnp.asarray(lowercase__ ) return unflatten_dict(lowercase__ )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( 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 , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''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))
636
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : Optional[int] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : Optional[Any] , a_ : Union[str, Any] , a_ : List[str]=0 )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : str = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : Any )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 'french fries' SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : str = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Optional[int] = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : str = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[Any] = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : int )-> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : List[Any] = components['vae'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Optional[Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[int] )-> Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : int , a_ : Union[str, Any]=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : str = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_inputs() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_inputs() SCREAMING_SNAKE_CASE__ : int = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : List[str] = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Any = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Optional[int] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : int = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : int = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images[0] SCREAMING_SNAKE_CASE__ : Optional[int] = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = {"vocab_file": "spiece.model"} SCREAMING_SNAKE_CASE__ : int = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } SCREAMING_SNAKE_CASE__ : Optional[int] = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Tuple = 4 class snake_case ( UpperCamelCase_ ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = 'left' def __init__( self : List[Any] , a_ : Union[str, Any] , a_ : int=False , a_ : Optional[Any]=True , a_ : Dict=False , a_ : str="<s>" , a_ : Optional[Any]="</s>" , a_ : int="<unk>" , a_ : Optional[Any]="<sep>" , a_ : Dict="<pad>" , a_ : Any="<cls>" , a_ : int="<mask>" , a_ : Optional[Any]=["<eop>", "<eod>"] , a_ : Optional[Dict[str, Any]] = None , **a_ : Tuple , )-> None: """simple docstring""" __A : List[str] = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token __A : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) __A : Dict = 3 __A : int = do_lower_case __A : Optional[int] = remove_space __A : Tuple = keep_accents __A : Tuple = vocab_file __A : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return len(self.sp_model ) def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" __A : Any = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict )-> Any: """simple docstring""" __A : Any = self.__dict__.copy() __A : int = None return state def __setstate__( self : Dict , a_ : Tuple )-> str: """simple docstring""" __A : Dict = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __A : Union[str, Any] = {} __A : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowercase( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" if self.remove_space: __A : Dict = ' '.join(inputs.strip().split() ) else: __A : List[Any] = inputs __A : List[Any] = outputs.replace('``' , '"' ).replace('\'\'' , '"' ) if not self.keep_accents: __A : Any = unicodedata.normalize('NFKD' , a_ ) __A : Optional[Any] = ''.join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: __A : Dict = outputs.lower() return outputs def __lowercase( self : Any , a_ : str )-> List[str]: """simple docstring""" __A : Tuple = self.preprocess_text(a_ ) __A : Tuple = self.sp_model.encode(a_ , out_type=a_ ) __A : Any = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str(',' ) and piece[-2].isdigit(): __A : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , '' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __A : Dict = cur_pieces[1:] else: __A : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def __lowercase( self : List[str] , a_ : Union[str, Any] )-> List[str]: """simple docstring""" return self.sp_model.PieceToId(a_ ) def __lowercase( self : Optional[Any] , a_ : Optional[Any] )-> Optional[Any]: """simple docstring""" return self.sp_model.IdToPiece(a_ ) def __lowercase( self : str , a_ : Any )-> int: """simple docstring""" __A : Dict = ''.join(a_ ).replace(a_ , ' ' ).strip() return out_string def __lowercase( self : Dict , a_ : List[int] , a_ : bool = False , a_ : bool = None , a_ : bool = True , **a_ : Dict , )-> str: """simple docstring""" __A : int = kwargs.pop('use_source_tokenizer' , a_ ) __A : int = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __A : Dict = [] __A : List[Any] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) __A : Any = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens __A : Optional[int] = ''.join(a_ ) __A : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __A : List[str] = self.clean_up_tokenization(a_ ) return clean_text else: return text def __lowercase( self : Any , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" __A : List[Any] = [self.sep_token_id] __A : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowercase( self : str , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False )-> List[int]: """simple docstring""" 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 not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def __lowercase( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" __A : str = [self.sep_token_id] __A : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowercase( self : Union[str, Any] , a_ : str , a_ : Optional[str] = None )-> Tuple[str]: """simple docstring""" if not os.path.isdir(a_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __A : Any = os.path.join( a_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , 'wb' ) as fi: __A : List[str] = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def _a ( lowercase__ : str ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = np.max(_outputs , axis=-1 , keepdims=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase__ ) class snake_case ( UpperCamelCase_ ): lowercase_ = 'sigmoid' lowercase_ = 'softmax' lowercase_ = 'none' @add_end_docstrings( UpperCamelCase_ , r'\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `"default"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `"sigmoid"`: Applies the sigmoid function on the output.\n - `"softmax"`: Applies the softmax function on the output.\n - `"none"`: Does not apply any function on the output.\n ' , ) class snake_case ( UpperCamelCase_ ): lowercase_ = False lowercase_ = ClassificationFunction.NONE def __init__( self : Tuple , **a_ : Dict )-> List[str]: """simple docstring""" super().__init__(**a_ ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def __lowercase( self : Union[str, Any] , a_ : str=None , a_ : Any=None , a_ : Optional[Any]="" , **a_ : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_kwargs SCREAMING_SNAKE_CASE__ : Tuple = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: SCREAMING_SNAKE_CASE__ : Dict = self.model.config.return_all_scores if isinstance(a_ , a_ ) or top_k is None: SCREAMING_SNAKE_CASE__ : int = top_k SCREAMING_SNAKE_CASE__ : List[str] = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a_ , ) if return_all_scores: SCREAMING_SNAKE_CASE__ : Tuple = None else: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : int = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : List[str] , *a_ : List[Any] , **a_ : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = super().__call__(*a_ , **a_ ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE__ : int = 'top_k' not in kwargs if isinstance(args[0] , a_ ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def __lowercase( self : str , a_ : Optional[Any] , **a_ : List[Any] )-> Dict[str, GenericTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.framework if isinstance(a_ , a_ ): return self.tokenizer(**a_ , return_tensors=a_ , **a_ ) elif isinstance(a_ , a_ ) and len(a_ ) == 1 and isinstance(inputs[0] , a_ ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a_ , **a_ ) elif isinstance(a_ , a_ ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(a_ , return_tensors=a_ , **a_ ) def __lowercase( self : List[str] , a_ : Tuple )-> List[Any]: """simple docstring""" return self.model(**a_ ) def __lowercase( self : str , a_ : Tuple , a_ : Union[str, Any]=None , a_ : str=1 , a_ : Union[str, Any]=True )-> Any: """simple docstring""" # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE__ : Tuple = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE__ : List[str] = ClassificationFunction.NONE SCREAMING_SNAKE_CASE__ : int = model_outputs['logits'][0] SCREAMING_SNAKE_CASE__ : Tuple = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE__ : Optional[int] = sigmoid(a_ ) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE__ : str = softmax(a_ ) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE__ : Dict = outputs else: raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}''' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE__ : Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a_ ) ] if not _legacy: dict_scores.sort(key=lambda a_ : x["score"] , reverse=a_ ) if top_k is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = dict_scores[:top_k] return dict_scores
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( 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 , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
import os import pytest from transformers.dynamic_module_utils import get_imports SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\nimport os\n" SCREAMING_SNAKE_CASE__ : List[Any] = "\ndef foo():\n import os\n return False\n" SCREAMING_SNAKE_CASE__ : str = "\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n" SCREAMING_SNAKE_CASE__ : Any = "\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : int = "\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Dict = "\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Dict = "\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : List[str] = "\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : List[str] = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Optional[int] = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : int = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('case' , lowercase__ ) def _a ( lowercase__ : Optional[Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(lowercase__ , 'test_file.py' ) with open(lowercase__ , 'w' ) as _tmp_file: _tmp_file.write(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_imports(lowercase__ ) assert parsed_imports == ["os"]
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[int]] = [[0 for _ in range(lowercase__ )] for _ in range(m + 1 )] for i in range(m + 1 ): SCREAMING_SNAKE_CASE__ : Any = 1 for n in range(m + 1 ): for k in range(1 , lowercase__ ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: SCREAMING_SNAKE_CASE__ : Dict = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: SCREAMING_SNAKE_CASE__ : int = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class snake_case : @staticmethod def __lowercase( *a_ : Union[str, Any] , **a_ : int )-> Tuple: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class snake_case ( unittest.TestCase ): lowercase_ = MODEL_FOR_OBJECT_DETECTION_MAPPING def __lowercase( self : str , a_ : List[str] , a_ : int , a_ : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ObjectDetectionPipeline(model=a_ , image_processor=a_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def __lowercase( self : Any , a_ : Tuple , a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png' , threshold=0.0 ) self.assertGreater(len(a_ ) , 0 ) for detected_object in outputs: self.assertEqual( a_ , { 'score': ANY(a_ ), 'label': ANY(a_ ), 'box': {'xmin': ANY(a_ ), 'ymin': ANY(a_ ), 'xmax': ANY(a_ ), 'ymax': ANY(a_ )}, } , ) import datasets SCREAMING_SNAKE_CASE__ : Tuple = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) SCREAMING_SNAKE_CASE__ : List[str] = [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] SCREAMING_SNAKE_CASE__ : str = object_detector(a_ , threshold=0.0 ) self.assertEqual(len(a_ ) , len(a_ ) ) for outputs in batch_outputs: self.assertGreater(len(a_ ) , 0 ) for detected_object in outputs: self.assertEqual( a_ , { 'score': ANY(a_ ), 'label': ANY(a_ ), 'box': {'xmin': ANY(a_ ), 'ymin': ANY(a_ ), 'xmax': ANY(a_ ), 'ymax': ANY(a_ )}, } , ) @require_tf @unittest.skip('Object detection not implemented in TF' ) def __lowercase( self : Dict )-> Any: """simple docstring""" pass @require_torch def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 'hf-internal-testing/tiny-detr-mobilenetsv3' SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoModelForObjectDetection.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Any = AutoFeatureExtractor.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : str = ObjectDetectionPipeline(model=a_ , feature_extractor=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=0.0 ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ] , ) SCREAMING_SNAKE_CASE__ : List[str] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], ] , ) @require_torch @slow def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : List[str] = AutoModelForObjectDetection.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ObjectDetectionPipeline(model=a_ , feature_extractor=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : Optional[int] = pipeline('object-detection' , model=a_ ) SCREAMING_SNAKE_CASE__ : Dict = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 0.9985 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : Any = pipeline('object-detection' , model=a_ ) SCREAMING_SNAKE_CASE__ : Dict = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=a_ ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) @require_torch @require_pytesseract @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 'Narsil/layoutlmv3-finetuned-funsd' SCREAMING_SNAKE_CASE__ : str = 0.9993 SCREAMING_SNAKE_CASE__ : List[str] = pipeline('object-detection' , model=a_ , threshold=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = object_detector( 'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, ] , )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import gc import threading import time import psutil import torch class snake_case : def __init__( self : Dict )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = psutil.Process() SCREAMING_SNAKE_CASE__ : Optional[Any] = False def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = -1 while True: SCREAMING_SNAKE_CASE__ : Optional[int] = 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 __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Optional[int] = threading.Thread(target=self.peak_monitor ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True self.thread.start() def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = False self.thread.join() return self.cpu_memory_peak SCREAMING_SNAKE_CASE__ : Union[str, Any] = PeakCPUMemory() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = {'time': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : Tuple = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : Dict = torch.cuda.memory_allocated(lowercase__ ) torch.cuda.reset_peak_memory_stats() return measures def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = {'time': time.time() - start_measures['time']} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : Union[str, Any] = (psutil.Process().memory_info().rss - start_measures['cpu']) / 2**20 SCREAMING_SNAKE_CASE__ : int = (cpu_peak_tracker.stop() - start_measures['cpu']) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : Dict = (torch.cuda.memory_allocated(lowercase__ ) - start_measures[str(lowercase__ )]) / 2**20 SCREAMING_SNAKE_CASE__ : List[Any] = (torch.cuda.max_memory_allocated(lowercase__ ) - start_measures[str(lowercase__ )]) / 2**20 return measures def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''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(lowercase__ )]:.2f}MiB''' ) SCREAMING_SNAKE_CASE__ : Any = 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''' )
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , *a_ : int , **a_ : Optional[int] )-> None: """simple docstring""" warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a_ , ) super().__init__(*a_ , **a_ )
711
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) # TODO: upload to AWS SCREAMING_SNAKE_CASE__ : Optional[int] = { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json" ), } class snake_case ( UpperCamelCase_ ): lowercase_ = 'retribert' def __init__( self : Any , a_ : Optional[Any]=3_0522 , a_ : Optional[int]=768 , a_ : Union[str, Any]=8 , a_ : Dict=12 , a_ : Optional[Any]=3072 , a_ : Dict="gelu" , a_ : Dict=0.1 , a_ : List[Any]=0.1 , a_ : List[Any]=512 , a_ : List[str]=2 , a_ : Tuple=0.02 , a_ : int=1e-1_2 , a_ : Optional[int]=True , a_ : List[Any]=128 , a_ : List[Any]=0 , **a_ : List[Any] , )-> List[str]: """simple docstring""" super().__init__(pad_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = share_encoders SCREAMING_SNAKE_CASE__ : Optional[int] = projection_dim
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
SCREAMING_SNAKE_CASE__ : Optional[int] = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" SCREAMING_SNAKE_CASE__ : str = [{"type": "code", "content": INSTALL_CONTENT}] SCREAMING_SNAKE_CASE__ : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : int , a_ : bool = True , a_ : Dict[str, int] = None , a_ : int = 0.9 , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : bool = True , a_ : Dict[str, int] = None , 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_ : List[Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = crop_size if crop_size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE__ : str = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : List[Any] = do_resize SCREAMING_SNAKE_CASE__ : Optional[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = crop_pct SCREAMING_SNAKE_CASE__ : Union[str, Any] = resample SCREAMING_SNAKE_CASE__ : Tuple = do_center_crop SCREAMING_SNAKE_CASE__ : Optional[Any] = crop_size SCREAMING_SNAKE_CASE__ : Any = do_rescale SCREAMING_SNAKE_CASE__ : List[Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE__ : List[str] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN SCREAMING_SNAKE_CASE__ : Any = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __lowercase( self : Union[str, Any] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[float] = None , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Dict , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(a_ , default_to_square=a_ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(F'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) if crop_pct is not None: if "shortest_edge" in size: SCREAMING_SNAKE_CASE__ : Dict = int(size['shortest_edge'] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: SCREAMING_SNAKE_CASE__ : Optional[Any] = int(size['height'] / crop_pct ) else: SCREAMING_SNAKE_CASE__ : Any = (int(size['height'] / crop_pct ), int(size['width'] / crop_pct )) else: raise ValueError('Invalid size for resize: {}'.format(a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_resize_output_image_size(a_ , size=a_ , default_to_square=a_ ) else: if "shortest_edge" in size: SCREAMING_SNAKE_CASE__ : str = get_resize_output_image_size(a_ , size=size['shortest_edge'] , default_to_square=a_ ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (size['height'], size['width']) else: raise ValueError('Invalid size for resize: {}'.format(a_ ) ) return resize(a_ , size=a_ , resample=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[str] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Dict , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(a_ , size=(size['height'], size['width']) , data_format=a_ , **a_ ) def __lowercase( self : str , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> str: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[Any] , a_ : np.ndarray , a_ : Union[float, List[float]] , a_ : Union[float, List[float]] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> np.ndarray: """simple docstring""" return normalize(a_ , mean=a_ , std=a_ , data_format=a_ , **a_ ) def __lowercase( self : Optional[int] , a_ : ImageInput , a_ : bool = None , a_ : Dict[str, int] = None , a_ : int = None , a_ : PILImageResampling = None , a_ : bool = None , a_ : Dict[str, int] = None , a_ : bool = None , a_ : float = 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_ : str , )-> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : str = crop_pct if crop_pct is not None else self.crop_pct SCREAMING_SNAKE_CASE__ : Optional[Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : int = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : Any = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Any = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : int = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_pct is None: raise ValueError('Crop_pct must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Optional[Any] = [to_numpy_array(a_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : int = [self.resize(image=a_ , size=a_ , crop_pct=a_ , resample=a_ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE__ : str = [self.center_crop(image=a_ , size=a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Any = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.normalize(image=a_ , mean=a_ , std=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[int] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Any = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
def _a ( lowercase__ : Any , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _a ( lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 while b > 0: if b & 1: SCREAMING_SNAKE_CASE__ : Any = ((res % c) + (a % c)) % c a += a b >>= 1 return res
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _a ( lowercase__ : int ): '''simple docstring''' random.seed(lowercase__ ) np.random.seed(lowercase__ ) torch.manual_seed(lowercase__ ) torch.cuda.manual_seed_all(lowercase__ ) # ^^ safe to call this function even if cuda is not available class snake_case : def __init__( self : Any , a_ : Iterable[torch.nn.Parameter] , a_ : float = 0.9999 , a_ : float = 0.0 , a_ : int = 0 , a_ : bool = False , a_ : Union[float, int] = 1.0 , a_ : Union[float, int] = 2 / 3 , a_ : Optional[Any] = None , a_ : Dict[str, Any] = None , **a_ : Optional[int] , )-> Dict: """simple docstring""" if isinstance(a_ , torch.nn.Module ): SCREAMING_SNAKE_CASE__ : str = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage`' , '1.0.0' , a_ , standard_warn=a_ , ) SCREAMING_SNAKE_CASE__ : Dict = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility SCREAMING_SNAKE_CASE__ : Any = True if kwargs.get('max_value' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : Any = 'The `max_value` argument is deprecated. Please use `decay` instead.' deprecate('max_value' , '1.0.0' , a_ , standard_warn=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs['max_value'] if kwargs.get('min_value' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : List[str] = 'The `min_value` argument is deprecated. Please use `min_decay` instead.' deprecate('min_value' , '1.0.0' , a_ , standard_warn=a_ ) SCREAMING_SNAKE_CASE__ : int = kwargs['min_value'] SCREAMING_SNAKE_CASE__ : Optional[int] = list(a_ ) SCREAMING_SNAKE_CASE__ : Dict = [p.clone().detach() for p in parameters] if kwargs.get('device' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'The `device` argument is deprecated. Please use `to` instead.' deprecate('device' , '1.0.0' , a_ , standard_warn=a_ ) self.to(device=kwargs['device'] ) SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Optional[int] = decay SCREAMING_SNAKE_CASE__ : Optional[Any] = min_decay SCREAMING_SNAKE_CASE__ : int = update_after_step SCREAMING_SNAKE_CASE__ : Optional[Any] = use_ema_warmup SCREAMING_SNAKE_CASE__ : Union[str, Any] = inv_gamma SCREAMING_SNAKE_CASE__ : str = power SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : List[str] = None # set in `step()` SCREAMING_SNAKE_CASE__ : Tuple = model_cls SCREAMING_SNAKE_CASE__ : Optional[Any] = model_config @classmethod def __lowercase( cls : Any , a_ : List[Any] , a_ : str )-> "EMAModel": """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_cls.load_config(a_ , return_unused_kwargs=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_cls.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = cls(model.parameters() , model_cls=a_ , model_config=model.config ) ema_model.load_state_dict(a_ ) return ema_model def __lowercase( self : List[str] , a_ : List[Any] )-> List[Any]: """simple docstring""" if self.model_cls is None: raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' ) if self.model_config is None: raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' ) SCREAMING_SNAKE_CASE__ : Tuple = self.model_cls.from_config(self.model_config ) SCREAMING_SNAKE_CASE__ : List[str] = self.state_dict() state_dict.pop('shadow_params' , a_ ) model.register_to_config(**a_ ) self.copy_to(model.parameters() ) model.save_pretrained(a_ ) def __lowercase( self : Optional[int] , a_ : int )-> float: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: SCREAMING_SNAKE_CASE__ : int = 1 - (1 + step / self.inv_gamma) ** -self.power else: SCREAMING_SNAKE_CASE__ : List[Any] = (1 + step) / (10 + step) SCREAMING_SNAKE_CASE__ : str = min(a_ , self.decay ) # make sure decay is not smaller than min_decay SCREAMING_SNAKE_CASE__ : int = max(a_ , self.min_decay ) return cur_decay_value @torch.no_grad() def __lowercase( self : int , a_ : Iterable[torch.nn.Parameter] )-> Optional[Any]: """simple docstring""" if isinstance(a_ , torch.nn.Module ): SCREAMING_SNAKE_CASE__ : Any = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' , '1.0.0' , a_ , standard_warn=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = parameters.parameters() SCREAMING_SNAKE_CASE__ : Optional[Any] = list(a_ ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. SCREAMING_SNAKE_CASE__ : Dict = self.get_decay(self.optimization_step ) SCREAMING_SNAKE_CASE__ : Optional[int] = decay SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 - decay SCREAMING_SNAKE_CASE__ : str = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , a_ ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): SCREAMING_SNAKE_CASE__ : Optional[int] = deepspeed.zero.GatheredParameters(a_ , modifier_rank=a_ ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(a_ ) def __lowercase( self : Union[str, Any] , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = list(a_ ) for s_param, param in zip(self.shadow_params , a_ ): param.data.copy_(s_param.to(param.device ).data ) def __lowercase( self : Optional[int] , a_ : Any=None , a_ : Dict=None )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ p.to(device=a_ , dtype=a_ ) if p.is_floating_point() else p.to(device=a_ ) for p in self.shadow_params ] def __lowercase( self : Union[str, Any] )-> dict: """simple docstring""" return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def __lowercase( self : Optional[Any] , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [param.detach().cpu().clone() for param in parameters] def __lowercase( self : Dict , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" if self.temp_stored_params is None: raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' ) for c_param, param in zip(self.temp_stored_params , a_ ): param.data.copy_(c_param.data ) # Better memory-wise. SCREAMING_SNAKE_CASE__ : Optional[int] = None def __lowercase( self : Any , a_ : dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = copy.deepcopy(a_ ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('decay' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('Decay must be between 0 and 1' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.get('min_decay' , self.min_decay ) if not isinstance(self.min_decay , a_ ): raise ValueError('Invalid min_decay' ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('optimization_step' , self.optimization_step ) if not isinstance(self.optimization_step , a_ ): raise ValueError('Invalid optimization_step' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.get('update_after_step' , self.update_after_step ) if not isinstance(self.update_after_step , a_ ): raise ValueError('Invalid update_after_step' ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('use_ema_warmup' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , a_ ): raise ValueError('Invalid use_ema_warmup' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.get('inv_gamma' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('Invalid inv_gamma' ) SCREAMING_SNAKE_CASE__ : str = state_dict.get('power' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('Invalid power' ) SCREAMING_SNAKE_CASE__ : str = state_dict.get('shadow_params' , a_ ) if shadow_params is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = shadow_params if not isinstance(self.shadow_params , a_ ): raise ValueError('shadow_params must be a list' ) if not all(isinstance(a_ , torch.Tensor ) for p in self.shadow_params ): raise ValueError('shadow_params must all be Tensors' )
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = 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_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" 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 __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'mgp-str' def __init__( self : Dict , a_ : Optional[int]=[32, 128] , a_ : List[str]=4 , a_ : List[Any]=3 , a_ : Union[str, Any]=27 , a_ : Optional[Any]=38 , a_ : Any=5_0257 , a_ : Tuple=3_0522 , a_ : Any=768 , a_ : Union[str, Any]=12 , a_ : List[Any]=12 , a_ : Tuple=4.0 , a_ : Union[str, Any]=True , a_ : Optional[Any]=False , a_ : Tuple=1e-5 , a_ : List[Any]=0.0 , a_ : Any=0.0 , a_ : int=0.0 , a_ : Optional[int]=False , a_ : int=0.02 , **a_ : List[str] , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : List[Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_token_length SCREAMING_SNAKE_CASE__ : Tuple = num_character_labels SCREAMING_SNAKE_CASE__ : List[Any] = num_bpe_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_wordpiece_labels SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = mlp_ratio SCREAMING_SNAKE_CASE__ : Dict = distilled SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = drop_rate SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : Dict = attn_drop_rate SCREAMING_SNAKE_CASE__ : List[str] = drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = output_aa_attentions SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "xlm-mlm-en-2048": "https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json", "xlm-mlm-ende-1024": "https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json", "xlm-mlm-enfr-1024": "https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json", "xlm-mlm-enro-1024": "https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json", "xlm-mlm-tlm-xnli15-1024": "https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json", "xlm-mlm-xnli15-1024": "https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json", "xlm-clm-enfr-1024": "https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json", "xlm-clm-ende-1024": "https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json", "xlm-mlm-17-1280": "https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json", "xlm-mlm-100-1280": "https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'xlm' lowercase_ = { 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self : List[Any] , a_ : Tuple=3_0145 , a_ : Union[str, Any]=2048 , a_ : int=12 , a_ : List[Any]=16 , a_ : str=0.1 , a_ : Union[str, Any]=0.1 , a_ : Optional[int]=True , a_ : Dict=False , a_ : Optional[Any]=False , a_ : Optional[Any]=False , a_ : List[Any]=1 , a_ : int=True , a_ : Dict=512 , a_ : List[str]=2048**-0.5 , a_ : Tuple=1e-1_2 , a_ : Optional[int]=0.02 , a_ : Any=0 , a_ : Optional[int]=1 , a_ : Union[str, Any]=2 , a_ : List[Any]=3 , a_ : List[str]=5 , a_ : Optional[int]=True , a_ : List[str]="first" , a_ : int=True , a_ : Union[str, Any]=None , a_ : Optional[int]=True , a_ : Tuple=0.1 , a_ : Any=5 , a_ : List[str]=5 , a_ : List[str]=0 , a_ : Any=0 , a_ : Dict=2 , a_ : List[Any]=0 , **a_ : Optional[int] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = emb_dim SCREAMING_SNAKE_CASE__ : Dict = n_layers SCREAMING_SNAKE_CASE__ : Any = n_heads SCREAMING_SNAKE_CASE__ : int = dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Any = gelu_activation SCREAMING_SNAKE_CASE__ : List[Any] = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = causal SCREAMING_SNAKE_CASE__ : Union[str, Any] = asm SCREAMING_SNAKE_CASE__ : int = n_langs SCREAMING_SNAKE_CASE__ : Any = use_lang_emb SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = bos_index SCREAMING_SNAKE_CASE__ : Tuple = eos_index SCREAMING_SNAKE_CASE__ : str = pad_index SCREAMING_SNAKE_CASE__ : Union[str, Any] = unk_index SCREAMING_SNAKE_CASE__ : str = mask_index SCREAMING_SNAKE_CASE__ : Dict = is_encoder SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = embed_init_std SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Dict = summary_type SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_use_proj SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_activation SCREAMING_SNAKE_CASE__ : str = summary_proj_to_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_first_dropout SCREAMING_SNAKE_CASE__ : Tuple = start_n_top SCREAMING_SNAKE_CASE__ : Tuple = end_n_top SCREAMING_SNAKE_CASE__ : List[Any] = mask_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = lang_id if "n_words" in kwargs: SCREAMING_SNAKE_CASE__ : str = kwargs['n_words'] super().__init__(pad_token_id=a_ , bos_token_id=a_ , **a_ ) class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : List[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0