code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import RoFormerConfig, 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 ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class SCREAMING_SNAKE_CASE : def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=32 , _UpperCAmelCase=2 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=16 , _UpperCAmelCase=2 , _UpperCAmelCase=0.02 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=None , ): '''simple docstring''' __A : List[str] = parent __A : int = 13 __A : Optional[int] = 7 __A : int = True __A : List[str] = True __A : str = True __A : int = True __A : int = 99 __A : str = 32 __A : Tuple = 2 __A : int = 4 __A : str = 37 __A : List[str] = """gelu""" __A : Tuple = 0.1 __A : Tuple = 0.1 __A : Optional[Any] = 512 __A : Union[str, Any] = 16 __A : Optional[Any] = 2 __A : Union[str, Any] = 0.02 __A : Union[str, Any] = 3 __A : Tuple = 4 __A : List[Any] = None def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __A : List[Any] = None if self.use_input_mask: __A : int = random_attention_mask([self.batch_size, self.seq_length]) __A : Any = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __A : Dict = None __A : List[Any] = None __A : Dict = None if self.use_labels: __A : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __A : int = ids_tensor([self.batch_size] , self.num_choices) __A : Optional[Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=_UpperCAmelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : int = TFRoFormerModel(config=_UpperCAmelCase) __A : int = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} __A : int = [input_ids, input_mask] __A : Tuple = model(_UpperCAmelCase) __A : Union[str, Any] = model(_UpperCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Optional[Any] = True __A : Any = TFRoFormerForCausalLM(config=_UpperCAmelCase) __A : Union[str, Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __A : Dict = model(_UpperCAmelCase)["""logits"""] self.parent.assertListEqual( list(prediction_scores.numpy().shape) , [self.batch_size, self.seq_length, self.vocab_size]) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Union[str, Any] = TFRoFormerForMaskedLM(config=_UpperCAmelCase) __A : Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __A : Optional[int] = model(_UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : List[str] = self.num_labels __A : Optional[int] = TFRoFormerForSequenceClassification(config=_UpperCAmelCase) __A : Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __A : Tuple = model(_UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : List[Any] = self.num_choices __A : List[Any] = TFRoFormerForMultipleChoice(config=_UpperCAmelCase) __A : Optional[int] = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1)) __A : Any = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1)) __A : int = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1)) __A : List[str] = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } __A : List[str] = model(_UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Any = self.num_labels __A : Tuple = TFRoFormerForTokenClassification(config=_UpperCAmelCase) __A : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __A : Union[str, Any] = model(_UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : int = TFRoFormerForQuestionAnswering(config=_UpperCAmelCase) __A : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } __A : Optional[int] = model(_UpperCAmelCase) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = self.prepare_config_and_inputs() ( __A ) : Any = config_and_inputs __A : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE (UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCAmelCase = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) lowerCAmelCase = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) lowerCAmelCase = False lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = TFRoFormerModelTester(self) __A : Any = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_UpperCAmelCase) @slow def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : str = TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base') self.assertIsNotNone(_UpperCAmelCase) @require_tf class SCREAMING_SNAKE_CASE (unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base') __A : Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]]) __A : Optional[Any] = model(_UpperCAmelCase)[0] # TODO Replace vocab size __A : Tuple = 5_0000 __A : Optional[int] = [1, 6, vocab_size] self.assertEqual(output.shape , _UpperCAmelCase) print(output[:, :3, :3]) # TODO Replace values below with what was printed above. __A : Dict = tf.constant( [ [ [-0.12053341, -1.0264901, 0.29221946], [-1.5133783, 0.197433, 0.15190607], [-5.0135403, -3.900256, -0.84038764], ] ]) tf.debugging.assert_near(output[:, :3, :3] , _UpperCAmelCase , atol=1e-4) @require_tf class SCREAMING_SNAKE_CASE (unittest.TestCase ): lowerCAmelCase = 1E-4 def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = tf.constant([[4, 10]]) __A : int = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6) __A : Optional[Any] = emba(input_ids.shape) __A : Union[str, Any] = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]]) tf.debugging.assert_near(_UpperCAmelCase , _UpperCAmelCase , atol=self.tolerance) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ]) __A : Tuple = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512) emba([2, 16, 512]) __A : Union[str, Any] = emba.weight[:3, :5] tf.debugging.assert_near(_UpperCAmelCase , _UpperCAmelCase , atol=self.tolerance) @require_tf class SCREAMING_SNAKE_CASE (unittest.TestCase ): lowerCAmelCase = 1E-4 def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 100 __A : int = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 100 __A : List[str] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64) __A : List[Any] = embed_positions([2, 16, 768])[None, None, :, :] __A : Dict = TFRoFormerSelfAttention.apply_rotary_position_embeddings( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) __A : Any = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ]) __A : Dict = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ]) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , _UpperCAmelCase , atol=self.tolerance) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , _UpperCAmelCase , atol=self.tolerance)
190
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class __lowercase (UpperCAmelCase__ ): """simple docstring""" _snake_case = 42 class __lowercase (UpperCAmelCase__ , UpperCAmelCase__ ): """simple docstring""" @register_to_config def __init__( self , A = 3 , A = 3 , A = ("DownEncoderBlock2D",) , A = ("UpDecoderBlock2D",) , A = (6_4,) , A = 1 , A = "silu" , A = 3 , A = 3_2 , A = 2_5_6 , A = 3_2 , A = None , A = 0.1_82_15 , A = "group" , ) -> Optional[int]: super().__init__() # pass init params to Encoder snake_case : Union[str, Any] = Encoder( in_channels=A , out_channels=A , down_block_types=A , block_out_channels=A , layers_per_block=A , act_fn=A , norm_num_groups=A , double_z=A , ) snake_case : Optional[int] = vq_embed_dim if vq_embed_dim is not None else latent_channels snake_case : Optional[int] = nn.Convad(A , A , 1 ) snake_case : str = VectorQuantizer(A , A , beta=0.25 , remap=A , sane_index_shape=A ) snake_case : List[str] = nn.Convad(A , A , 1 ) # pass init params to Decoder snake_case : List[str] = Decoder( in_channels=A , out_channels=A , up_block_types=A , block_out_channels=A , layers_per_block=A , act_fn=A , norm_num_groups=A , norm_type=A , ) @apply_forward_hook def UpperCAmelCase ( self , A , A = True ) -> VQEncoderOutput: snake_case : Optional[int] = self.encoder(A ) snake_case : int = self.quant_conv(A ) if not return_dict: return (h,) return VQEncoderOutput(latents=A ) @apply_forward_hook def UpperCAmelCase ( self , A , A = False , A = True ) -> Union[DecoderOutput, torch.FloatTensor]: # also go through quantization layer if not force_not_quantize: snake_case : Tuple = self.quantize(A ) else: snake_case : str = h snake_case : Dict = self.post_quant_conv(A ) snake_case : Union[str, Any] = self.decoder(A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=A ) def UpperCAmelCase ( self , A , A = True ) -> Union[DecoderOutput, torch.FloatTensor]: snake_case : Tuple = sample snake_case : int = self.encode(A ).latents snake_case : List[Any] = self.decode(A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=A )
124
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> int: lowerCAmelCase = prime_factors(_UpperCAmelCase ) if is_square_free(_UpperCAmelCase ): return -1 if len(_UpperCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
338
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
0
from math import isqrt def _a ( SCREAMING_SNAKE_CASE_ : int ): return all(number % divisor != 0 for divisor in range(2 , isqrt(_UpperCAmelCase ) + 1 ) ) def _a ( SCREAMING_SNAKE_CASE_ : int = 10**6 ): __lowerCAmelCase = 0 __lowerCAmelCase = 1 __lowerCAmelCase = 7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f'''{solution() = }''')
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
from ....utils import logging A_ : Any = logging.get_logger(__name__) class _a (UpperCAmelCase__ ): '''simple docstring''' def __init__( self , A__ , A__=None , A__=2048 ): A__ : str = config.__dict__ A__ : Tuple = modal_hidden_size if num_labels: A__ : Tuple = num_labels
192
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
0
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor __lowerCamelCase : List[Any] = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self , *A_ , **A_ ): '''simple docstring''' warnings.warn( "The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use LayoutLMv2ImageProcessor instead." , A_ , ) super().__init__(*A_ , **A_ )
52
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
0
"""simple docstring""" from typing import Dict from .base import GenericTensor, Pipeline class lowercase( UpperCAmelCase__ ): '''simple docstring''' def UpperCamelCase_ ( self: Dict, a_: List[str]=None, a_: str=None, a_: Any=None, **a_: int ): '''simple docstring''' if tokenize_kwargs is None: _snake_case : Tuple = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) _snake_case : Union[str, Any] = truncation _snake_case : List[str] = tokenize_kwargs _snake_case : Any = {} if return_tensors is not None: _snake_case : List[str] = return_tensors return preprocess_params, {}, postprocess_params def UpperCamelCase_ ( self: Tuple, a_: Union[str, Any], **a_: str ): '''simple docstring''' _snake_case : Optional[int] = self.framework _snake_case : int = self.tokenizer(a_, return_tensors=a_, **a_ ) return model_inputs def UpperCamelCase_ ( self: List[Any], a_: Any ): '''simple docstring''' _snake_case : List[str] = self.model(**a_ ) return model_outputs def UpperCamelCase_ ( self: Union[str, Any], a_: int, a_: Any=False ): '''simple docstring''' if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self: List[str], *a_: Optional[Any], **a_: List[Any] ): '''simple docstring''' return super().__call__(*a_, **a_ )
64
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''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 __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
0
"""simple docstring""" import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) lowercase__ : Union[str, Any] = pytest.mark.integration @pytest.mark.parametrize('''path''' , ['''paws''', '''csv'''] ) def __lowercase ( _a , _a ): inspect_dataset(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : Any = path + """.py""" assert script_name in os.listdir(_UpperCAmelCase ) assert "__pycache__" not in os.listdir(_UpperCAmelCase ) @pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.parametrize('''path''' , ['''accuracy'''] ) def __lowercase ( _a , _a ): inspect_metric(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : List[Any] = path + """.py""" assert script_name in os.listdir(_UpperCAmelCase ) assert "__pycache__" not in os.listdir(_UpperCAmelCase ) @pytest.mark.parametrize( '''path, config_name, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def __lowercase ( _a , _a , _a ): snake_case_ : str = get_dataset_config_info(_UpperCAmelCase , config_name=_UpperCAmelCase ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def __lowercase ( _a , _a , _a ): with pytest.raises(_UpperCAmelCase ): get_dataset_config_info(_UpperCAmelCase , config_name=_UpperCAmelCase ) @pytest.mark.parametrize( '''path, expected''' , [ ('''squad''', '''plain_text'''), ('''acronym_identification''', '''default'''), ('''lhoestq/squad''', '''plain_text'''), ('''lhoestq/test''', '''default'''), ('''lhoestq/demo1''', '''lhoestq--demo1'''), ('''dalle-mini/wit''', '''dalle-mini--wit'''), ] , ) def __lowercase ( _a , _a ): snake_case_ : Optional[Any] = get_dataset_config_names(_UpperCAmelCase ) assert expected in config_names @pytest.mark.parametrize( '''path, expected_configs, expected_splits_in_first_config''' , [ ('''squad''', ['''plain_text'''], ['''train''', '''validation''']), ('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']), ('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']), ] , ) def __lowercase ( _a , _a , _a ): snake_case_ : Union[str, Any] = get_dataset_infos(_UpperCAmelCase ) assert list(infos.keys() ) == expected_configs snake_case_ : Tuple = expected_configs[0] assert expected_config in infos snake_case_ : str = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( '''path, expected_config, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def __lowercase ( _a , _a , _a ): snake_case_ : Dict = get_dataset_infos(_UpperCAmelCase ) assert expected_config in infos snake_case_ : Union[str, Any] = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def __lowercase ( _a , _a , _a ): with pytest.raises(_UpperCAmelCase ): get_dataset_split_names(_UpperCAmelCase , config_name=_UpperCAmelCase )
264
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
0
import argparse import os import re import packaging.version __snake_case = '''examples/''' __snake_case = { '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } __snake_case = { '''init''': '''src/diffusers/__init__.py''', '''setup''': '''setup.py''', } __snake_case = '''README.md''' def _A ( _lowercase , _lowercase , _lowercase ) -> Tuple: """simple docstring""" with open(_UpperCAmelCase , 'r' , encoding='utf-8' , newline='\n' ) as f: __UpperCamelCase = f.read() __UpperCamelCase = REPLACE_PATTERNS[pattern] __UpperCamelCase = replace.replace('VERSION' , _UpperCAmelCase ) __UpperCamelCase = re_pattern.sub(_UpperCAmelCase , _UpperCAmelCase ) with open(_UpperCAmelCase , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(_UpperCAmelCase ) def _A ( _lowercase ) -> Tuple: """simple docstring""" for folder, directories, fnames in os.walk(_UpperCAmelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , _UpperCAmelCase , pattern='examples' ) def _A ( _lowercase , _lowercase=False ) -> List[Any]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if not patch: update_version_in_examples(_UpperCAmelCase ) def _A ( ) -> Any: """simple docstring""" __UpperCamelCase = """🤗 Transformers currently provides the following architectures""" __UpperCamelCase = """1. Want to contribute a new model?""" with open(_UpperCAmelCase , 'r' , encoding='utf-8' , newline='\n' ) as f: __UpperCamelCase = f.readlines() # Find the start of the list. __UpperCamelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __UpperCamelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): __UpperCamelCase = lines[index].replace( 'https://huggingface.co/docs/diffusers/main/model_doc' , 'https://huggingface.co/docs/diffusers/model_doc' , ) index += 1 with open(_UpperCAmelCase , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(_UpperCAmelCase ) def _A ( ) -> List[Any]: """simple docstring""" with open(REPLACE_FILES['init'] , 'r' ) as f: __UpperCamelCase = f.read() __UpperCamelCase = REPLACE_PATTERNS["""init"""][0].search(_UpperCAmelCase ).groups()[0] return packaging.version.parse(_UpperCAmelCase ) def _A ( _lowercase=False ) -> str: """simple docstring""" __UpperCamelCase = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: __UpperCamelCase = default_version.base_version elif patch: __UpperCamelCase = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: __UpperCamelCase = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. __UpperCamelCase = input(f'''Which version are you releasing? [{default_version}]''' ) if len(_UpperCAmelCase ) == 0: __UpperCamelCase = default_version print(f'''Updating version to {version}.''' ) global_version_update(_UpperCAmelCase , patch=_UpperCAmelCase ) def _A ( ) -> Optional[int]: """simple docstring""" __UpperCamelCase = get_version() __UpperCamelCase = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' __UpperCamelCase = current_version.base_version # Check with the user we got that right. __UpperCamelCase = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(_UpperCAmelCase ) == 0: __UpperCamelCase = dev_version print(f'''Updating version to {version}.''' ) global_version_update(_UpperCAmelCase ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') __snake_case = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
310
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( """features""" ,[ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
0
"""simple docstring""" from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def A ( snake_case :bool = True , *snake_case :Optional[Any] , **snake_case :Dict ) -> List[str]: if not is_tqdm_available(): raise ImportError('Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.' ) __UpperCamelCase = False if main_process_only: __UpperCamelCase = PartialState().local_process_index == 0 return _tqdm(*_UpperCAmelCase , **_UpperCAmelCase , disable=_UpperCAmelCase )
316
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
0
a_ = '''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
340
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( 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 A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor lowercase__ : Union[str, Any] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE (UpperCAmelCase__ ): def __init__( self , *_UpperCAmelCase , **_UpperCAmelCase): '''simple docstring''' warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _UpperCAmelCase , ) super().__init__(*_UpperCAmelCase , **_UpperCAmelCase)
190
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
0
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> float: return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(_UpperCAmelCase ,_UpperCAmelCase ) ) ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> list[list[list[float] | float]]: if dataset.ndim != value_array.ndim: snake_case : int = ( """Wrong input data's dimensions... """ f"""dataset : {dataset.ndim}, value_array : {value_array.ndim}""" ) raise ValueError(_UpperCAmelCase ) try: if dataset.shape[1] != value_array.shape[1]: snake_case : Optional[Any] = ( """Wrong input data's shape... """ f"""dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}""" ) raise ValueError(_UpperCAmelCase ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: snake_case : Tuple = ( """Input data have different datatype... """ f"""dataset : {dataset.dtype}, value_array : {value_array.dtype}""" ) raise TypeError(_UpperCAmelCase ) snake_case : Dict = [] for value in value_array: snake_case : Optional[int] = euclidean(_UpperCAmelCase ,dataset[0] ) snake_case : List[Any] = dataset[0].tolist() for dataset_value in dataset[1:]: snake_case : Any = euclidean(_UpperCAmelCase ,_UpperCAmelCase ) if dist > temp_dist: snake_case : Any = temp_dist snake_case : int = dataset_value.tolist() answer.append([vector, dist] ) return answer def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> float: return np.dot(_UpperCAmelCase ,_UpperCAmelCase ) / (norm(_UpperCAmelCase ) * norm(_UpperCAmelCase )) if __name__ == "__main__": import doctest doctest.testmod()
124
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase__ : List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[int] = ['''ChineseCLIPFeatureExtractor'''] lowercase__ : Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys lowercase__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
338
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
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 a__ ( UpperCAmelCase__ , unittest.TestCase ): _a : int = CLIPTokenizer _a : Dict = CLIPTokenizerFast _a : List[str] = True _a : Optional[Any] = {} _a : str = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # fmt: off __lowerCAmelCase = ["""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 __lowerCAmelCase = dict(zip(_A , range(len(_A ) ) ) ) __lowerCAmelCase = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>"""] __lowerCAmelCase = {"""unk_token""": """<unk>"""} __lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(_A ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(_A ) ) def __SCREAMING_SNAKE_CASE( self , **_A ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **_A ) def __SCREAMING_SNAKE_CASE( self , **_A ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = """lower newer""" __lowerCAmelCase = """lower newer""" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCAmelCase = """lower newer""" __lowerCAmelCase = ["""lo""", """w""", """er</w>""", """n""", """e""", """w""", """er</w>"""] __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokens + [tokenizer.unk_token] __lowerCAmelCase = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , _A ) @require_ftfy def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowerCAmelCase = self.tokenizer_class.from_pretrained(_A , **_A ) __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __lowerCAmelCase = """A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d.""" __lowerCAmelCase = tokenizer_s.tokenize(_A ) __lowerCAmelCase = tokenizer_r.tokenize(_A ) self.assertListEqual(_A , _A ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCAmelCase = """xa\u0303y""" + """ """ + """x\xe3y""" __lowerCAmelCase = tokenizer_s.tokenize(_A ) __lowerCAmelCase = tokenizer_r.tokenize(_A ) self.assertListEqual(_A , _A ) # Test that the tokenization is identical on unicode of space type __lowerCAmelCase = [ """\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: __lowerCAmelCase = tokenizer_s.tokenize(_A ) __lowerCAmelCase = tokenizer_r.tokenize(_A ) self.assertListEqual(_A , _A ) # Test that the tokenization is identical on unicode of line break type __lowerCAmelCase = [ """\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: __lowerCAmelCase = tokenizer_s.tokenize(_A ) __lowerCAmelCase = tokenizer_r.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowerCAmelCase = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` __lowerCAmelCase = f"""{text_of_1_token} {text_of_1_token}""" __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _A , use_fast=_A , ) __lowerCAmelCase = tokenizer_r(_A , return_offsets_mapping=_A , add_special_tokens=_A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_A ) + 1, len(_A ) + 1 + len(_A )) , ) __lowerCAmelCase = f""" {text}""" __lowerCAmelCase = self.rust_tokenizer_class.from_pretrained( _A , use_fast=_A , ) __lowerCAmelCase = tokenizer_r(_A , return_offsets_mapping=_A , add_special_tokens=_A ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_A ) + 1, 1 + len(_A ) + 1 + len(_A )) , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" with self.assertRaises(_A ) 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().test_tokenization_python_rust_equals() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass
92
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
0
from collections import defaultdict def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Optional[Any] = first_str.lower().strip() A__ : List[str] = second_str.lower().strip() # Remove whitespace A__ : int = first_str.replace(""" """ , """""" ) A__ : List[Any] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): return False # Default values for count should be 0 A__ : defaultdict[str, int] = defaultdict(_UpperCAmelCase ) # For each character in input strings, # increment count in the corresponding for i in range(len(_UpperCAmelCase ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() A_ : Tuple = input('Enter the first string ').strip() A_ : Optional[int] = input('Enter the second string ').strip() A_ : int = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
192
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
0
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": __lowerCamelCase : Union[str, Any] = input("""Enter image url: """).strip() print(f"""Downloading image from {url} ...""") __lowerCamelCase : Tuple = BeautifulSoup(requests.get(url).content, """html.parser""") # The image URL is in the content field of the first meta tag with property og:image __lowerCamelCase : Union[str, Any] = soup.find("""meta""", {"""property""": """og:image"""})['''content'''] __lowerCamelCase : List[Any] = requests.get(image_url).content __lowerCamelCase : List[str] = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, """wb""") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
52
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
0
"""simple docstring""" import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A_ = None A_ = { '''7B''': 1_10_08, '''13B''': 1_38_24, '''30B''': 1_79_20, '''65B''': 2_20_16, '''70B''': 2_86_72, } A_ = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def UpperCAmelCase__ (snake_case__ : Optional[int] , snake_case__ : Optional[int]=1 , snake_case__ : List[str]=2_56 ): """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(_UpperCAmelCase , """r""" ) as f: return json.load(_UpperCAmelCase ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Optional[Any] ): """simple docstring""" with open(_UpperCAmelCase , """w""" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Optional[Any] , snake_case__ : int , snake_case__ : List[Any]=True ): """simple docstring""" os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) _snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase , """tmp""" ) os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) _snake_case : int = read_json(os.path.join(_UpperCAmelCase , """params.json""" ) ) _snake_case : int = NUM_SHARDS[model_size] _snake_case : Dict = params["""n_layers"""] _snake_case : Union[str, Any] = params["""n_heads"""] _snake_case : List[str] = n_heads // num_shards _snake_case : int = params["""dim"""] _snake_case : Union[str, Any] = dim // n_heads _snake_case : int = 1_00_00.0 _snake_case : str = 1.0 / (base ** (torch.arange(0 , _UpperCAmelCase , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: _snake_case : str = params["""n_kv_heads"""] # for GQA / MQA _snake_case : Optional[Any] = n_heads_per_shard // num_key_value_heads _snake_case : Optional[int] = dim // num_key_value_heads else: # compatibility with other checkpoints _snake_case : str = n_heads _snake_case : Any = n_heads_per_shard _snake_case : str = dim # permute for sliced rotary def permute(snake_case__ : Tuple , snake_case__ : Optional[int]=n_heads , snake_case__ : Optional[int]=dim , snake_case__ : List[str]=dim ): return w.view(_UpperCAmelCase , dima // n_heads // 2 , 2 , _UpperCAmelCase ).transpose(1 , 2 ).reshape(_UpperCAmelCase , _UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _snake_case : Any = torch.load(os.path.join(_UpperCAmelCase , """consolidated.00.pth""" ) , map_location="""cpu""" ) else: # Sharded _snake_case : List[Any] = [ torch.load(os.path.join(_UpperCAmelCase , F"consolidated.{i:02d}.pth" ) , map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _snake_case : Any = 0 _snake_case : Optional[int] = {"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _snake_case : List[str] = F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _snake_case : List[str] = { F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _snake_case : Tuple = { F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _snake_case : str = permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) ) _snake_case : Tuple = permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) _snake_case : Any = torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) _snake_case : List[str] = torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] , dim=1 ) _snake_case : Union[str, Any] = torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] , dim=0 ) _snake_case : Tuple = torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] , dim=1 ) _snake_case : Union[str, Any] = torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] , dim=0 ) _snake_case : str = inv_freq for k, v in state_dict.items(): _snake_case : Any = filename param_count += v.numel() torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase ) ) _snake_case : Union[str, Any] = F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _snake_case : List[str] = { """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _snake_case : int = { """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] , dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] , dim=0 ), } for k, v in state_dict.items(): _snake_case : Dict = filename param_count += v.numel() torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase ) ) # Write configs _snake_case : Tuple = {"""total_size""": param_count * 2} write_json(_UpperCAmelCase , os.path.join(_UpperCAmelCase , """pytorch_model.bin.index.json""" ) ) _snake_case : Optional[Any] = params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _snake_case : int = params["""multiple_of"""] if """multiple_of""" in params else 2_56 _snake_case : List[Any] = LlamaConfig( hidden_size=_UpperCAmelCase , intermediate_size=compute_intermediate_size(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , num_attention_heads=params["""n_heads"""] , num_hidden_layers=params["""n_layers"""] , rms_norm_eps=params["""norm_eps"""] , num_key_value_heads=_UpperCAmelCase , ) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _snake_case : Any = LlamaForCausalLM.from_pretrained(_UpperCAmelCase , torch_dtype=torch.floataa , low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase , safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" _snake_case : List[str] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _snake_case : List[Any] = tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[str] = argparse.ArgumentParser() parser.add_argument( """--input_dir""" , help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" , ) parser.add_argument( """--model_size""" , choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] , ) parser.add_argument( """--output_dir""" , help="""Location to write HF model and tokenizer""" , ) parser.add_argument("""--safe_serialization""" , type=_UpperCAmelCase , help="""Whether or not to save using `safetensors`.""" ) _snake_case : Optional[Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) _snake_case : List[Any] = os.path.join(args.input_dir , """tokenizer.model""" ) write_tokenizer(args.output_dir , _UpperCAmelCase ) if __name__ == "__main__": main()
64
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
0
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowercase__ : Optional[int] = random.Random() def __lowercase ( _a , _a=1.0 , _a=None , _a=None ): if rng is None: snake_case_ : Optional[int] = global_rng 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 @require_torchaudio class _UpperCAmelCase ( unittest.TestCase): def __init__( self : str , lowercase_ : List[str] , lowercase_ : Tuple=7 , lowercase_ : Union[str, Any]=400 , lowercase_ : str=2000 , lowercase_ : str=10 , lowercase_ : Tuple=160 , lowercase_ : List[str]=8 , lowercase_ : Optional[int]=0.0 , lowercase_ : Union[str, Any]=4000 , lowercase_ : Optional[int]=False , lowercase_ : List[str]=True , ): snake_case_ : List[Any] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : int = min_seq_length snake_case_ : Tuple = max_seq_length snake_case_ : List[str] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case_ : List[Any] = padding_value snake_case_ : int = sampling_rate snake_case_ : List[str] = return_attention_mask snake_case_ : Union[str, Any] = do_normalize snake_case_ : Tuple = feature_size snake_case_ : str = chunk_length snake_case_ : Any = hop_length def _snake_case ( self : Dict ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _snake_case ( self : Any , lowercase_ : List[str]=False , lowercase_ : Any=False ): def _flatten(lowercase_ : Optional[int] ): return list(itertools.chain(*lowercase_ ) ) if equal_length: snake_case_ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case_ : Optional[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case_ : str = [np.asarray(lowercase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase): _lowerCAmelCase : Union[str, Any] = WhisperFeatureExtractor if is_speech_available() else None def _snake_case ( self : List[Any] ): snake_case_ : Optional[int] = WhisperFeatureExtractionTester(self ) def _snake_case ( self : Optional[Any] ): snake_case_ : int = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = feat_extract_first.save_pretrained(lowercase_ )[0] check_json_file_has_correct_format(lowercase_ ) snake_case_ : Optional[Any] = self.feature_extraction_class.from_pretrained(lowercase_ ) snake_case_ : Optional[Any] = feat_extract_first.to_dict() snake_case_ : Optional[int] = feat_extract_second.to_dict() snake_case_ : str = feat_extract_first.mel_filters snake_case_ : List[str] = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowercase_ , lowercase_ ) ) self.assertEqual(lowercase_ , lowercase_ ) def _snake_case ( self : Dict ): snake_case_ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = os.path.join(lowercase_ , '''feat_extract.json''' ) feat_extract_first.to_json_file(lowercase_ ) snake_case_ : Dict = self.feature_extraction_class.from_json_file(lowercase_ ) snake_case_ : int = feat_extract_first.to_dict() snake_case_ : Any = feat_extract_second.to_dict() snake_case_ : List[str] = feat_extract_first.mel_filters snake_case_ : List[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowercase_ , lowercase_ ) ) self.assertEqual(lowercase_ , lowercase_ ) def _snake_case ( self : Tuple ): snake_case_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case_ : List[str] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] snake_case_ : str = [np.asarray(lowercase_ ) for speech_input in speech_inputs] # Test feature size snake_case_ : Any = feature_extractor(lowercase_ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case_ : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case_ : Optional[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) ) # Test batched snake_case_ : Optional[int] = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ): self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. snake_case_ : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case_ : List[str] = np.asarray(lowercase_ ) snake_case_ : Optional[Any] = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features snake_case_ : Optional[Any] = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ): self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) ) # Test truncation required snake_case_ : Dict = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case_ : Dict = [np.asarray(lowercase_ ) for speech_input in speech_inputs] snake_case_ : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case_ : Dict = [np.asarray(lowercase_ ) for speech_input in speech_inputs_truncated] snake_case_ : Dict = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(lowercase_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ): self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) ) def _snake_case ( self : int ): import torch snake_case_ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : int = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case_ : Optional[int] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case_ : str = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case_ : Union[str, Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _snake_case ( self : List[Any] , lowercase_ : Tuple ): snake_case_ : Optional[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case_ : Optional[Any] = ds.sort('''id''' ).select(range(lowercase_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _snake_case ( self : str ): snake_case_ : Any = torch.tensor( [ 0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51, 0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78, 0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54, -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54 ] ) # fmt: on snake_case_ : Any = self._load_datasamples(1 ) snake_case_ : int = WhisperFeatureExtractor() snake_case_ : str = feature_extractor(lowercase_ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , lowercase_ , atol=1E-4 ) ) def _snake_case ( self : Any ): snake_case_ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : str = self._load_datasamples(1 )[0] snake_case_ : List[Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535 # Rescale to [0, 65535] to show issue snake_case_ : Union[str, Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=lowercase_ )[0] self.assertTrue(np.all(np.mean(lowercase_ ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowercase_ ) - 1 ) < 1E-3 ) )
264
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
0
from ..utils import DummyObject, requires_backends class __lowerCamelCase (metaclass=UpperCAmelCase__ ): _lowercase = ["torch", "torchsde"] def __init__( self: Optional[int],*A_: Optional[int],**A_: Optional[int] ): '''simple docstring''' requires_backends(self,['torch', 'torchsde'] ) @classmethod def snake_case_ ( cls: Dict,*A_: Optional[Any],**A_: List[str] ): '''simple docstring''' requires_backends(cls,['torch', 'torchsde'] ) @classmethod def snake_case_ ( cls: Optional[Any],*A_: Union[str, Any],**A_: int ): '''simple docstring''' requires_backends(cls,['torch', 'torchsde'] )
310
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
0
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class __lowerCAmelCase ( unittest.TestCase ): def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = [10, 20, 30, 40, 50, 60] __UpperCamelCase = [2, 4, 6, 8, 10, 12] __UpperCamelCase = 100 self.assertEqual(kp.calc_profit(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) , 210 ) def UpperCAmelCase ( self ): '''simple docstring''' self.assertRaisesRegex(__UpperCAmelCase , 'max_weight must greater than zero.' ) def UpperCAmelCase ( self ): '''simple docstring''' self.assertRaisesRegex(__UpperCAmelCase , 'Weight can not be negative.' ) def UpperCAmelCase ( self ): '''simple docstring''' self.assertRaisesRegex(__UpperCAmelCase , 'Profit can not be negative.' ) def UpperCAmelCase ( self ): '''simple docstring''' self.assertRaisesRegex(__UpperCAmelCase , 'max_weight must greater than zero.' ) def UpperCAmelCase ( self ): '''simple docstring''' self.assertRaisesRegex( __UpperCAmelCase , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
316
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase__ ( UpperCAmelCase__ ): @staticmethod @abstractmethod def UpperCAmelCase ( __UpperCAmelCase )-> Dict: '''simple docstring''' raise NotImplementedError() @abstractmethod def UpperCAmelCase ( self )-> List[str]: '''simple docstring''' raise NotImplementedError()
340
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
0
'''simple docstring''' import numpy as np import qiskit def _lowerCAmelCase ( __snake_case : int = 8 , __snake_case : int | None = None ) -> str: __A : int = np.random.default_rng(seed=_UpperCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __A : Dict = 6 * key_len # Measurement basis for Alice's qubits. __A : Optional[int] = rng.integers(2 , size=_UpperCAmelCase ) # The set of states Alice will prepare. __A : Optional[int] = rng.integers(2 , size=_UpperCAmelCase ) # Measurement basis for Bob's qubits. __A : List[str] = rng.integers(2 , size=_UpperCAmelCase ) # Quantum Circuit to simulate BB84 __A : Optional[Any] = qiskit.QuantumCircuit(_UpperCAmelCase , name='BB84' ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_UpperCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(_UpperCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(_UpperCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_UpperCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(_UpperCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __A : Dict = qiskit.Aer.get_backend('aer_simulator' ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __A : Union[str, Any] = qiskit.execute(_UpperCAmelCase , _UpperCAmelCase , shots=1 , seed_simulator=_UpperCAmelCase ) # Returns the result of measurement. __A : Optional[Any] = job.result().get_counts(_UpperCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __A : str = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __A : List[Any] = gen_key[:key_len] if len(_UpperCAmelCase ) >= key_len else gen_key.ljust(_UpperCAmelCase , '0' ) return key if __name__ == "__main__": print(f"""The generated key is : {bbaa(8, seed=0)}""") from doctest import testmod testmod()
190
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
0
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Union[str, Any]: snake_case : Tuple = 1 snake_case : List[str] = 2 while i * i <= n: snake_case : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def SCREAMING_SNAKE_CASE__ ( ) -> Union[str, Any]: snake_case : List[Any] = 1 snake_case : int = 1 while True: i += 1 t_num += i if count_divisors(_UpperCAmelCase ) > 500: break return t_num if __name__ == "__main__": print(solution())
124
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin lowercase__ : Union[str, Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') lowercase__ : int = {'''target_lang''': '''fi''', '''source_lang''': '''en'''} lowercase__ : Dict = '''>>zh<<''' lowercase__ : Optional[Any] = '''Helsinki-NLP/''' if is_torch_available(): lowercase__ : Optional[int] = '''pt''' elif is_tf_available(): lowercase__ : int = '''tf''' else: lowercase__ : Optional[Any] = '''jax''' @require_sentencepiece class lowercase_ ( UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ : int = MarianTokenizer UpperCAmelCase_ : str = False UpperCAmelCase_ : int = True def SCREAMING_SNAKE_CASE_ ( self ) ->Any: super().setUp() lowerCAmelCase = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCAmelCase = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) lowerCAmelCase = Path(self.tmpdirname ) save_json(__SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''vocab'''] ) save_json(__SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''tokenizer_config_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''source_spm'''] ) copyfile(__SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''target_spm'''] ) lowerCAmelCase = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self , **__SCREAMING_SNAKE_CASE ) ->MarianTokenizer: return MarianTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE ) ->Any: return ( "This is a test", "This is a test", ) def SCREAMING_SNAKE_CASE_ ( self ) ->Dict: lowerCAmelCase = """</s>""" lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self ) ->Optional[Any]: lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 9 ) def SCREAMING_SNAKE_CASE_ ( self ) ->Dict: self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def SCREAMING_SNAKE_CASE_ ( self ) ->Optional[int]: lowerCAmelCase = MarianTokenizer.from_pretrained(F"{ORG_NAME}opus-mt-en-de" ) lowerCAmelCase = en_de_tokenizer(['''I am a small frog'''] , return_tensors=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowerCAmelCase = [38, 121, 14, 697, 38848, 0] self.assertListEqual(__SCREAMING_SNAKE_CASE , batch.input_ids[0] ) lowerCAmelCase = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) lowerCAmelCase = [x.name for x in Path(__SCREAMING_SNAKE_CASE ).glob('''*''' )] self.assertIn('''source.spm''' , __SCREAMING_SNAKE_CASE ) MarianTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self ) ->str: lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = tok( ['''I am a small frog''' * 1000, '''I am a small frog'''] , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def SCREAMING_SNAKE_CASE_ ( self ) ->int: lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = tok(['''I am a tiny frog''', '''I am a small frog'''] , padding=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def SCREAMING_SNAKE_CASE_ ( self ) ->Optional[Any]: lowerCAmelCase = {"""input_ids""": [[43495, 462, 20, 42164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 38999, 6, 8, 464, 132, 1703, 492, 13, 4669, 37867, 13, 7525, 27, 1593, 988, 13, 33972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 12338, 2, 13958, 387, 2, 3629, 6953, 188, 2900, 2, 13958, 8011, 11501, 23, 8460, 4073, 34009, 20, 435, 11439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 37867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 26453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10767, 6, 316, 304, 4239, 3, 0], [148, 15722, 19, 1839, 12, 1350, 13, 22327, 5082, 5418, 47567, 35938, 59, 318, 19552, 108, 2183, 54, 14976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 19088, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100], [36, 6395, 12570, 39147, 11597, 6, 266, 4, 45405, 7296, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__SCREAMING_SNAKE_CASE , model_name='''Helsinki-NLP/opus-mt-en-de''' , revision='''1a8c2263da11e68e50938f97e10cd57820bd504c''' , decode_kwargs={'''use_source_tokenizer''': True} , ) def SCREAMING_SNAKE_CASE_ ( self ) ->str: lowerCAmelCase = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) lowerCAmelCase = """Tämä on testi""" lowerCAmelCase = """This is a test""" lowerCAmelCase = [76, 7, 2047, 2] lowerCAmelCase = [69, 12, 11, 940, 2] lowerCAmelCase = tokenizer(__SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowerCAmelCase = tokenizer(text_target=__SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowerCAmelCase = tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
338
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
0
from maths.prime_factors import prime_factors def _a ( SCREAMING_SNAKE_CASE_ : int ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): __lowerCAmelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(_UpperCAmelCase ) if number < 1: raise ValueError("Input must be a positive integer" ) return -1 if len(prime_factors(_UpperCAmelCase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class _a (UpperCAmelCase__ ): '''simple docstring''' def __A ( self ): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def __A ( self ): A__ : List[Any] = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A__ ) def __A ( self ): A__ : Dict = self._create_example_records() A__ : Dict = Dataset.from_list(A__ ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A__ ): self.assertDictEqual(A__ , example_records[i] ) def __A ( self ): A__ : Any = self._create_example_records() A__ : Union[str, Any] = Dataset.from_list(A__ ) A__ : Dict = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def __A ( self ): # checks what happens with missing columns A__ : Dict = [{"""col_1""": 1}, {"""col_2""": """x"""}] A__ : Dict = Dataset.from_list(A__ ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def __A ( self ): # checks if the type can be inferred from the second record A__ : Any = [{"""col_1""": []}, {"""col_1""": [1, 2]}] A__ : List[str] = Dataset.from_list(A__ ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def __A ( self ): A__ : Any = Dataset.from_list([] ) self.assertEqual(len(A__ ) , 0 ) self.assertListEqual(dset.column_names , [] )
192
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
0
import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def A_ ( _lowerCAmelCase ) -> Dict: UpperCamelCase : Dict = SwinConfig(image_size=192 ) if "base" in model_name: UpperCamelCase : List[Any] = 6 UpperCamelCase : Dict = 128 UpperCamelCase : Optional[Any] = (2, 2, 18, 2) UpperCamelCase : Any = (4, 8, 16, 32) elif "large" in model_name: UpperCamelCase : Dict = 12 UpperCamelCase : Dict = 192 UpperCamelCase : str = (2, 2, 18, 2) UpperCamelCase : Any = (6, 12, 24, 48) else: raise ValueError("Model not supported, only supports base and large variants" ) UpperCamelCase : Optional[int] = window_size UpperCamelCase : Union[str, Any] = embed_dim UpperCamelCase : Dict = depths UpperCamelCase : str = num_heads return config def A_ ( _lowerCAmelCase ) -> List[Any]: if "encoder.mask_token" in name: UpperCamelCase : List[str] = name.replace("encoder.mask_token" , "embeddings.mask_token" ) if "encoder.patch_embed.proj" in name: UpperCamelCase : str = name.replace("encoder.patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "encoder.patch_embed.norm" in name: UpperCamelCase : Union[str, Any] = name.replace("encoder.patch_embed.norm" , "embeddings.norm" ) if "attn.proj" in name: UpperCamelCase : Dict = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: UpperCamelCase : str = name.replace("attn" , "attention.self" ) if "norm1" in name: UpperCamelCase : List[Any] = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: UpperCamelCase : Any = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: UpperCamelCase : Optional[int] = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: UpperCamelCase : Dict = name.replace("mlp.fc2" , "output.dense" ) if name == "encoder.norm.weight": UpperCamelCase : Any = """layernorm.weight""" if name == "encoder.norm.bias": UpperCamelCase : Optional[Any] = """layernorm.bias""" if "decoder" in name: pass else: UpperCamelCase : List[Any] = """swin.""" + name return name def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Dict: for key in orig_state_dict.copy().keys(): UpperCamelCase : Tuple = orig_state_dict.pop(_UpperCAmelCase ) if "attn_mask" in key: pass elif "qkv" in key: UpperCamelCase : Tuple = key.split("." ) UpperCamelCase : Optional[int] = int(key_split[2] ) UpperCamelCase : List[Any] = int(key_split[4] ) UpperCamelCase : Union[str, Any] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase : List[Any] = val[:dim, :] UpperCamelCase : str = val[ dim : dim * 2, : ] UpperCamelCase : int = val[-dim:, :] else: UpperCamelCase : Optional[Any] = val[ :dim ] UpperCamelCase : Optional[Any] = val[ dim : dim * 2 ] UpperCamelCase : List[Any] = val[ -dim: ] else: UpperCamelCase : Optional[int] = val return orig_state_dict def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: UpperCamelCase : List[Any] = torch.load(_UpperCAmelCase , map_location="cpu" )["""model"""] UpperCamelCase : Any = get_swin_config(_UpperCAmelCase ) UpperCamelCase : Dict = SwinForMaskedImageModeling(_UpperCAmelCase ) model.eval() UpperCamelCase : Union[str, Any] = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) UpperCamelCase : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase : Any = ViTImageProcessor(size={"height": 192, "width": 192} ) UpperCamelCase : Any = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ) UpperCamelCase : Optional[Any] = image_processor(images=_UpperCAmelCase , return_tensors="pt" ) with torch.no_grad(): UpperCamelCase : Optional[int] = model(**_UpperCAmelCase ).logits print(outputs.keys() ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCAmelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: print(F"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(F"""microsoft/{model_name}""" ) image_processor.push_to_hub(F"""microsoft/{model_name}""" ) if __name__ == "__main__": __lowerCamelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""swin-base-simmim-window6-192""", type=str, choices=["""swin-base-simmim-window6-192""", """swin-large-simmim-window12-192"""], help="""Name of the Swin SimMIM model you\'d like to convert.""", ) parser.add_argument( """--checkpoint_path""", default="""/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth""", type=str, help="""Path to the original PyTorch checkpoint (.pth file).""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __lowerCamelCase : Optional[int] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
52
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
64
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''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 __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
0
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex lowercase__ : Dict = logging.getLogger(__name__) class _UpperCAmelCase : def __init__( self : int ): snake_case_ : Dict = False def _snake_case ( self : str , lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : str , lowercase_ : Any ): if not self.initialized: snake_case_ : Optional[Any] = RagRetriever( lowercase_ , question_encoder_tokenizer=lowercase_ , generator_tokenizer=lowercase_ , index=lowercase_ , init_retrieval=lowercase_ , ) snake_case_ : Optional[Any] = True def _snake_case ( self : Union[str, Any] ): self.retriever.index.init_index() def _snake_case ( self : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : int ): snake_case_ : Optional[Any] = self.retriever._main_retrieve(lowercase_ , lowercase_ ) return doc_ids, retrieved_doc_embeds class _UpperCAmelCase ( UpperCAmelCase__): def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[int]=None ): if index is not None and index.is_initialized() and len(lowercase_ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( lowercase_ , question_encoder_tokenizer=lowercase_ , generator_tokenizer=lowercase_ , index=lowercase_ , init_retrieval=lowercase_ , ) snake_case_ : int = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) for worker in self.retrieval_workers ] ) def _snake_case ( self : Dict ): logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def _snake_case ( self : Optional[int] , lowercase_ : Dict , lowercase_ : str ): if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. snake_case_ : List[str] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] snake_case_ : Dict = ray.get(random_worker.retrieve.remote(lowercase_ , lowercase_ ) ) else: snake_case_ : Union[str, Any] = self._main_retrieve(lowercase_ , lowercase_ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase_ ) @classmethod def _snake_case ( cls : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : Tuple=None , **lowercase_ : Any ): return super(lowercase_ , cls ).get_tokenizers(lowercase_ , lowercase_ , **lowercase_ ) @classmethod def _snake_case ( cls : Any , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : str=None , **lowercase_ : List[Any] ): snake_case_ : int = kwargs.pop('''config''' , lowercase_ ) or RagConfig.from_pretrained(lowercase_ , **lowercase_ ) snake_case_ : Optional[int] = RagTokenizer.from_pretrained(lowercase_ , config=lowercase_ ) snake_case_ : Dict = rag_tokenizer.question_encoder snake_case_ : Tuple = rag_tokenizer.generator if indexed_dataset is not None: snake_case_ : Dict = """custom""" snake_case_ : List[str] = CustomHFIndex(config.retrieval_vector_size , lowercase_ ) else: snake_case_ : Any = cls._build_index(lowercase_ ) return cls( lowercase_ , question_encoder_tokenizer=lowercase_ , generator_tokenizer=lowercase_ , retrieval_workers=lowercase_ , index=lowercase_ , )
264
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __snake_case = '''.''' if __name__ == "__main__": __snake_case = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') __snake_case = [] __snake_case = [] with open(doctest_file_path) as fp: for line in fp: __snake_case = line.strip() __snake_case = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __snake_case = '''\n'''.join(non_existent_paths) raise ValueError(f"""`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}""") if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
310
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( """features""" ,[ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
0
"""simple docstring""" 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 __lowerCAmelCase ( 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 UpperCAmelCase ( self , __UpperCAmelCase ): '''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] , __UpperCAmelCase ): raise ValueError(F'Column {self.label_column} is not a ClassLabel.' ) __UpperCamelCase = copy.deepcopy(self ) __UpperCamelCase = self.label_schema.copy() __UpperCamelCase = features[self.label_column] __UpperCamelCase = label_schema return task_template @property def UpperCAmelCase ( self ): '''simple docstring''' return { self.audio_column: "audio", self.label_column: "labels", }
316
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
0
a_ = ''' # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git ''' a_ = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] a_ = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
340
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( 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 A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
0
'''simple docstring''' def _lowerCAmelCase ( __snake_case : list ) -> list: if any(not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or x < 0 for x in sequence ): raise TypeError('Sequence must be list of non-negative integers' ) for _ in range(len(_UpperCAmelCase ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_UpperCAmelCase , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
190
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
0
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __lowercase (enum.Enum ): """simple docstring""" _snake_case = 0 _snake_case = 1 _snake_case = 2 @add_end_docstrings(UpperCAmelCase__ ) class __lowercase (UpperCAmelCase__ ): """simple docstring""" _snake_case = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self , *A , **A ) -> str: super().__init__(*A , **A ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. snake_case : int = None if self.model.config.prefix is not None: snake_case : Any = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. snake_case : Any = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. snake_case : Tuple = self._sanitize_parameters(prefix=A , **self._forward_params ) snake_case : Optional[int] = {**self._preprocess_params, **preprocess_params} snake_case : Tuple = {**self._forward_params, **forward_params} def UpperCAmelCase ( self , A=None , A=None , A=None , A=None , A=None , A=None , A=None , A=None , **A , ) -> Optional[int]: snake_case : Optional[int] = {} if prefix is not None: snake_case : Union[str, Any] = prefix if prefix: snake_case : Union[str, Any] = self.tokenizer( A , padding=A , add_special_tokens=A , return_tensors=self.framework ) snake_case : List[Any] = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" """ [None, 'hole']""" ) snake_case : List[Any] = handle_long_generation preprocess_params.update(A ) snake_case : Tuple = generate_kwargs snake_case : List[str] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) snake_case : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) snake_case : Any = ReturnType.TENSORS if return_type is not None: snake_case : Union[str, Any] = return_type if clean_up_tokenization_spaces is not None: snake_case : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: snake_case : str = self.tokenizer.encode(A , add_special_tokens=A ) if len(A ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) snake_case : Optional[int] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase ( self , *A , **A ) -> Optional[int]: # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*A , **A ) def __call__( self , A , **A ) -> int: return super().__call__(A , **A ) def UpperCAmelCase ( self , A , A="" , A=None , **A ) -> Any: snake_case : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=A , add_special_tokens=A , return_tensors=self.framework ) snake_case : Tuple = prompt_text if handle_long_generation == "hole": snake_case : Optional[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: snake_case : List[str] = generate_kwargs["""max_new_tokens"""] else: snake_case : Optional[Any] = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: snake_case : List[Any] = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) snake_case : int = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: snake_case : List[str] = inputs["""attention_mask"""][:, -keep_length:] return inputs def UpperCAmelCase ( self , A , **A ) -> List[str]: snake_case : int = model_inputs["""input_ids"""] snake_case : List[str] = model_inputs.get("""attention_mask""" , A ) # Allow empty prompts if input_ids.shape[1] == 0: snake_case : int = None snake_case : Optional[Any] = None snake_case : Any = 1 else: snake_case : Dict = input_ids.shape[0] snake_case : List[str] = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. snake_case : str = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: snake_case : Optional[int] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: snake_case : Union[str, Any] = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length snake_case : List[Any] = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL snake_case : Tuple = self.model.generate(input_ids=A , attention_mask=A , **A ) snake_case : int = generated_sequence.shape[0] if self.framework == "pt": snake_case : List[str] = generated_sequence.reshape(A , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": snake_case : List[str] = tf.reshape(A , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCAmelCase ( self , A , A=ReturnType.FULL_TEXT , A=True ) -> Optional[Any]: snake_case : Optional[int] = model_outputs["""generated_sequence"""][0] snake_case : Tuple = model_outputs["""input_ids"""] snake_case : Tuple = model_outputs["""prompt_text"""] snake_case : List[Any] = generated_sequence.numpy().tolist() snake_case : Dict = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: snake_case : Union[str, Any] = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text snake_case : int = self.tokenizer.decode( A , skip_special_tokens=A , clean_up_tokenization_spaces=A , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: snake_case : Tuple = 0 else: snake_case : List[Any] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=A , clean_up_tokenization_spaces=A , ) ) if return_type == ReturnType.FULL_TEXT: snake_case : Dict = prompt_text + text[prompt_length:] else: snake_case : int = text[prompt_length:] snake_case : str = {"""generated_text""": all_text} records.append(A ) return records
124
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
0
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowercase__ : int = logging.getLogger(__name__) @dataclass class lowercase_ : """simple docstring""" UpperCAmelCase_ : str UpperCAmelCase_ : List[str] UpperCAmelCase_ : Optional[List[str]] @dataclass class lowercase_ : """simple docstring""" UpperCAmelCase_ : List[int] UpperCAmelCase_ : List[int] UpperCAmelCase_ : Optional[List[int]] = None UpperCAmelCase_ : Optional[List[int]] = None class lowercase_ ( UpperCAmelCase__ ): """simple docstring""" UpperCAmelCase_ : str = "train" UpperCAmelCase_ : Tuple = "dev" UpperCAmelCase_ : str = "test" class lowercase_ : """simple docstring""" @staticmethod def SCREAMING_SNAKE_CASE_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->List[InputExample]: raise NotImplementedError @staticmethod def SCREAMING_SNAKE_CASE_ ( __SCREAMING_SNAKE_CASE ) ->List[str]: raise NotImplementedError @staticmethod def SCREAMING_SNAKE_CASE_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE="[CLS]" , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE="[SEP]" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=-100 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=True , ) ->List[InputFeatures]: lowerCAmelCase = {label: i for i, label in enumerate(__SCREAMING_SNAKE_CASE )} lowerCAmelCase = [] for ex_index, example in enumerate(__SCREAMING_SNAKE_CASE ): if ex_index % 10000 == 0: logger.info('''Writing example %d of %d''' , __SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) lowerCAmelCase = [] lowerCAmelCase = [] for word, label in zip(example.words , example.labels ): lowerCAmelCase = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__SCREAMING_SNAKE_CASE ) > 0: tokens.extend(__SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. lowerCAmelCase = tokenizer.num_special_tokens_to_add() if len(__SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: lowerCAmelCase = tokens[: (max_seq_length - special_tokens_count)] lowerCAmelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] lowerCAmelCase = [sequence_a_segment_id] * len(__SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: lowerCAmelCase = [cls_token] + tokens lowerCAmelCase = [pad_token_label_id] + label_ids lowerCAmelCase = [cls_token_segment_id] + segment_ids lowerCAmelCase = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. lowerCAmelCase = [1 if mask_padding_with_zero else 0] * len(__SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. lowerCAmelCase = max_seq_length - len(__SCREAMING_SNAKE_CASE ) if pad_on_left: lowerCAmelCase = ([pad_token] * padding_length) + input_ids lowerCAmelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask lowerCAmelCase = ([pad_token_segment_id] * padding_length) + segment_ids lowerCAmelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: lowerCAmelCase = None features.append( InputFeatures( input_ids=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , label_ids=__SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowercase_ ( UpperCAmelCase__ ): """simple docstring""" UpperCAmelCase_ : List[InputFeatures] UpperCAmelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE = Split.train , ) ->List[str]: lowerCAmelCase = os.path.join( __SCREAMING_SNAKE_CASE , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowerCAmelCase = cached_features_file + """.lock""" with FileLock(__SCREAMING_SNAKE_CASE ): if os.path.exists(__SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(F"Loading features from cached file {cached_features_file}" ) lowerCAmelCase = torch.load(__SCREAMING_SNAKE_CASE ) else: logger.info(F"Creating features from dataset file at {data_dir}" ) lowerCAmelCase = token_classification_task.read_examples_from_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers lowerCAmelCase = token_classification_task.convert_examples_to_features( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F"Saving features into cached file {cached_features_file}" ) torch.save(self.features , __SCREAMING_SNAKE_CASE ) def __len__( self ) ->Union[str, Any]: return len(self.features ) def __getitem__( self , __SCREAMING_SNAKE_CASE ) ->InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowercase_ : """simple docstring""" UpperCAmelCase_ : List[InputFeatures] UpperCAmelCase_ : int = -100 def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE = Split.train , ) ->Any: lowerCAmelCase = token_classification_task.read_examples_from_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers lowerCAmelCase = token_classification_task.convert_examples_to_features( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: lowerCAmelCase = tf.data.Dataset.from_generator( __SCREAMING_SNAKE_CASE , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: lowerCAmelCase = tf.data.Dataset.from_generator( __SCREAMING_SNAKE_CASE , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def SCREAMING_SNAKE_CASE_ ( self ) ->Any: lowerCAmelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self ) ->Optional[int]: return len(self.features ) def __getitem__( self , __SCREAMING_SNAKE_CASE ) ->InputFeatures: return self.features[i]
338
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) UpperCamelCase__ = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
0
A_ : Union[str, Any] = '''Alexander Joslin''' import operator as op from .stack import Stack def UpperCamelCase (lowercase_: str ) -> int: A__ : Optional[int] = {"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} A__ : Stack[int] = Stack() A__ : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase ) ) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase ) elif i == ")": # RULE 4 A__ : Union[str, Any] = operator_stack.peek() operator_stack.pop() A__ : int = operand_stack.peek() operand_stack.pop() A__ : Union[str, Any] = operand_stack.peek() operand_stack.pop() A__ : Any = operators[opr](_UpperCAmelCase , _UpperCAmelCase ) operand_stack.push(_UpperCAmelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A_ : Dict = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(f'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
192
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
0
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : def __init__( self , A_ , A_=13 , A_=32 , A_=3 , A_=4 , A_=[10, 20, 30, 40] , A_=[2, 2, 3, 2] , A_=True , A_=True , A_=37 , A_="gelu" , A_=10 , A_=0.02 , A_=["stage2", "stage3", "stage4"] , A_=[2, 3, 4] , A_=None , ): '''simple docstring''' UpperCamelCase : Any = parent UpperCamelCase : Union[str, Any] = batch_size UpperCamelCase : int = image_size UpperCamelCase : Optional[Any] = num_channels UpperCamelCase : Tuple = num_stages UpperCamelCase : List[Any] = hidden_sizes UpperCamelCase : Union[str, Any] = depths UpperCamelCase : List[str] = is_training UpperCamelCase : str = use_labels UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Any = num_labels UpperCamelCase : str = initializer_range UpperCamelCase : Optional[Any] = out_features UpperCamelCase : Any = out_indices UpperCamelCase : List[Any] = scope def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : Any = None if self.use_labels: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __UpperCamelCase( self ): '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=A_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Tuple = ConvNextVaModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model(A_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = ConvNextVaForImageClassification(A_ ) model.to(A_ ) model.eval() UpperCamelCase : Optional[Any] = model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = ConvNextVaBackbone(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Tuple = model(A_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = ConvNextVaBackbone(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Optional[int] = model(A_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.prepare_config_and_inputs() UpperCamelCase : Any = config_and_inputs UpperCamelCase : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.prepare_config_and_inputs() UpperCamelCase : List[Any] = config_and_inputs UpperCamelCase : Tuple = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): _UpperCAmelCase :Optional[int] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) _UpperCAmelCase :Tuple = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) _UpperCAmelCase :Any = False _UpperCAmelCase :Any = False _UpperCAmelCase :Optional[int] = False _UpperCAmelCase :Any = False _UpperCAmelCase :List[Any] = False def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = ConvNextVaModelTester(self ) UpperCamelCase : List[str] = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCamelCase( self ): '''simple docstring''' return @unittest.skip(reason="ConvNextV2 does not use inputs_embeds" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip(reason="ConvNextV2 does not support input and output embeddings" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip(reason="ConvNextV2 does not use feedforward chunking" ) def __UpperCamelCase( self ): '''simple docstring''' pass def __UpperCamelCase( self ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_with_labels() UpperCamelCase : Dict = True if model_class.__name__ in [ *get_values(A_ ), *get_values(A_ ), ]: continue UpperCamelCase : Union[str, Any] = model_class(A_ ) model.to(A_ ) model.train() UpperCamelCase : Optional[Any] = self._prepare_for_class(A_ , A_ , return_labels=A_ ) UpperCamelCase : List[Any] = model(**A_ ).loss loss.backward() def __UpperCamelCase( self ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_with_labels() UpperCamelCase : List[str] = False UpperCamelCase : Any = True if ( model_class.__name__ in [*get_values(A_ ), *get_values(A_ )] or not model_class.supports_gradient_checkpointing ): continue UpperCamelCase : List[str] = model_class(A_ ) model.to(A_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase : Union[str, Any] = self._prepare_for_class(A_ , A_ , return_labels=A_ ) UpperCamelCase : Any = model(**A_ ).loss loss.backward() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Any = model_class(A_ ) UpperCamelCase : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : Union[str, Any] = [*signature.parameters.keys()] UpperCamelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' def check_hidden_states_output(A_ , A_ , A_ ): UpperCamelCase : str = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCamelCase : Tuple = model(**self._prepare_for_class(A_ , A_ ) ) UpperCamelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase : str = self.model_tester.num_stages self.assertEqual(len(A_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : List[Any] = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase : List[Any] = True check_hidden_states_output(A_ , A_ , A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = ConvNextVaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def A_ ( ) -> List[str]: UpperCamelCase : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): @cached_property def __UpperCamelCase( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224" ) if is_vision_available() else None @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224" ).to(A_ ) UpperCamelCase : Tuple = self.default_image_processor UpperCamelCase : Optional[int] = prepare_img() UpperCamelCase : List[Any] = preprocessor(images=A_ , return_tensors="pt" ).to(A_ ) # forward pass with torch.no_grad(): UpperCamelCase : List[Any] = model(**A_ ) # verify the logits UpperCamelCase : Any = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , A_ ) UpperCamelCase : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1e-4 ) )
52
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
0
"""simple docstring""" import unittest import numpy as np def UpperCAmelCase__ (snake_case__ : np.ndarray , snake_case__ : np.ndarray , snake_case__ : np.ndarray , snake_case__ : np.ndarray | None = None , ): """simple docstring""" _snake_case : int = np.shape(_UpperCAmelCase ) _snake_case : Optional[Any] = np.shape(_UpperCAmelCase ) _snake_case : Optional[Any] = np.shape(_UpperCAmelCase ) if shape_a[0] != shape_b[0]: _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(_UpperCAmelCase ) if shape_b[1] != shape_c[1]: _snake_case : List[Any] = ( """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(_UpperCAmelCase ) _snake_case : Tuple = pseudo_inv if a_inv is None: try: _snake_case : str = np.linalg.inv(_UpperCAmelCase ) 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 lowercase( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Tuple = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _snake_case : Union[str, Any] = np.array([[0, 3], [3, 0], [2, 3]] ) _snake_case : List[Any] = np.array([[2, 1], [6, 3]] ) _snake_case : int = schur_complement(a_, a_, a_ ) _snake_case : Tuple = np.block([[a, b], [b.T, c]] ) _snake_case : Tuple = np.linalg.det(a_ ) _snake_case : Dict = np.linalg.det(a_ ) _snake_case : List[str] = np.linalg.det(a_ ) self.assertAlmostEqual(a_, det_a * det_s ) def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Optional[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _snake_case : Union[str, Any] = np.array([[0, 3], [3, 0], [2, 3]] ) _snake_case : List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(a_ ): schur_complement(a_, a_, a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : str = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _snake_case : int = np.array([[0, 3], [3, 0], [2, 3]] ) _snake_case : Tuple = 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()
64
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __lowercase ( _a ): snake_case_ : Tuple = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: snake_case_ : str = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: snake_case_ : str = 4 snake_case_ : Optional[int] = 48 snake_case_ : int = """pixelshuffle_aux""" elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: snake_case_ : Union[str, Any] = [6, 6, 6, 6] snake_case_ : Dict = 60 snake_case_ : int = [6, 6, 6, 6] snake_case_ : Dict = """pixelshuffledirect""" elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: snake_case_ : Union[str, Any] = 4 snake_case_ : Union[str, Any] = """nearest+conv""" elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: snake_case_ : Tuple = 1 snake_case_ : List[Any] = 1 snake_case_ : List[Any] = 126 snake_case_ : List[Any] = 7 snake_case_ : List[Any] = 255.0 snake_case_ : List[Any] = """""" return config def __lowercase ( _a , _a ): if "patch_embed.proj" in name and "layers" not in name: snake_case_ : str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case_ : str = name.replace('''patch_embed.norm''' , '''embeddings.patch_embeddings.layernorm''' ) if "layers" in name: snake_case_ : Any = name.replace('''layers''' , '''encoder.stages''' ) if "residual_group.blocks" in name: snake_case_ : Dict = name.replace('''residual_group.blocks''' , '''layers''' ) if "attn.proj" in name: snake_case_ : Optional[Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: snake_case_ : str = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case_ : Union[str, Any] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case_ : int = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case_ : List[str] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case_ : Dict = name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: snake_case_ : Union[str, Any] = name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: snake_case_ : Any = name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: snake_case_ : Dict = name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: snake_case_ : Dict = name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if "patch_embed.proj" in name: snake_case_ : Union[str, Any] = name.replace('''patch_embed.proj''' , '''patch_embed.projection''' ) if name == "norm.weight": snake_case_ : Dict = """layernorm.weight""" if name == "norm.bias": snake_case_ : Any = """layernorm.bias""" if "conv_first" in name: snake_case_ : Union[str, Any] = name.replace('''conv_first''' , '''first_convolution''' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: snake_case_ : Dict = name.replace('''conv_last''' , '''final_convolution''' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: snake_case_ : Optional[int] = name.replace('''conv_before_upsample.0''' , '''conv_before_upsample''' ) if "upsample.0" in name: snake_case_ : List[str] = name.replace('''upsample.0''' , '''upsample.convolution_0''' ) if "upsample.2" in name: snake_case_ : Any = name.replace('''upsample.2''' , '''upsample.convolution_1''' ) snake_case_ : List[Any] = """upsample.""" + name elif config.upsampler == "pixelshuffledirect": snake_case_ : Any = name.replace('''upsample.0.weight''' , '''upsample.conv.weight''' ) snake_case_ : Tuple = name.replace('''upsample.0.bias''' , '''upsample.conv.bias''' ) else: pass else: snake_case_ : List[str] = """swin2sr.""" + name return name def __lowercase ( _a , _a ): for key in orig_state_dict.copy().keys(): snake_case_ : Optional[Any] = orig_state_dict.pop(_UpperCAmelCase ) if "qkv" in key: snake_case_ : int = key.split('''.''' ) snake_case_ : List[Any] = int(key_split[1] ) snake_case_ : Union[str, Any] = int(key_split[4] ) snake_case_ : List[str] = config.embed_dim if "weight" in key: snake_case_ : Tuple = val[:dim, :] snake_case_ : Any = val[dim : dim * 2, :] snake_case_ : int = val[-dim:, :] else: snake_case_ : Any = val[:dim] snake_case_ : Optional[Any] = val[dim : dim * 2] snake_case_ : Optional[int] = val[-dim:] pass else: snake_case_ : Union[str, Any] = val return orig_state_dict def __lowercase ( _a , _a , _a ): snake_case_ : int = get_config(_UpperCAmelCase ) snake_case_ : Dict = SwinaSRForImageSuperResolution(_UpperCAmelCase ) model.eval() snake_case_ : Any = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location='''cpu''' ) snake_case_ : List[Any] = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : List[Any] = model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: raise ValueError('''Missing keys when converting: {}'''.format(_UpperCAmelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"Unexpected key {key} in state_dict" ) # verify values snake_case_ : str = """https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true""" snake_case_ : Any = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ).convert('''RGB''' ) snake_case_ : Optional[int] = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values snake_case_ : List[str] = 126 if """Jpeg""" in checkpoint_url else 256 snake_case_ : Dict = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) snake_case_ : Optional[int] = transforms(_UpperCAmelCase ).unsqueeze(0 ) if config.num_channels == 1: snake_case_ : str = pixel_values[:, 0, :, :].unsqueeze(1 ) snake_case_ : List[str] = model(_UpperCAmelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: snake_case_ : List[str] = torch.Size([1, 3, 512, 512] ) snake_case_ : Optional[Any] = torch.tensor( [[-0.7087, -0.7138, -0.6721], [-0.8340, -0.8095, -0.7298], [-0.9149, -0.8414, -0.7940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: snake_case_ : Tuple = torch.Size([1, 3, 1_024, 1_024] ) snake_case_ : Union[str, Any] = torch.tensor( [[-0.7775, -0.8105, -0.8933], [-0.7764, -0.8356, -0.9225], [-0.7976, -0.8686, -0.9579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here snake_case_ : Any = torch.Size([1, 3, 1_024, 1_024] ) snake_case_ : List[str] = torch.tensor( [[-0.8035, -0.7504, -0.7491], [-0.8538, -0.8124, -0.7782], [-0.8804, -0.8651, -0.8493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: snake_case_ : Optional[Any] = torch.Size([1, 3, 512, 512] ) snake_case_ : Union[str, Any] = torch.tensor( [[-0.7669, -0.8662, -0.8767], [-0.8810, -0.9962, -0.9820], [-0.9340, -1.0322, -1.1149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: snake_case_ : int = torch.Size([1, 3, 1_024, 1_024] ) snake_case_ : Tuple = torch.tensor( [[-0.5238, -0.5557, -0.6321], [-0.6016, -0.5903, -0.6391], [-0.6244, -0.6334, -0.6889]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , _UpperCAmelCase , atol=1E-3 ) print('''Looks ok!''' ) snake_case_ : Tuple = { """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth""": ( """swin2SR-classical-sr-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth""": ( """swin2SR-classical-sr-x4-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth""": ( """swin2SR-compressed-sr-x4-48""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth""": ( """swin2SR-lightweight-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth""": ( """swin2SR-realworld-sr-x4-64-bsrgan-psnr""" ), } snake_case_ : List[Any] = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCAmelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: model.push_to_hub(f"caidas/{model_name}" ) processor.push_to_hub(f"caidas/{model_name}" ) if __name__ == "__main__": lowercase__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR 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.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') lowercase__ : Optional[int] = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
264
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __snake_case = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
310
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
0
"""simple docstring""" import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters UpperCamelCase : str = logging.get_logger(__name__) def A ( snake_case :List[Any] , snake_case :List[str] , snake_case :int , snake_case :int=None , snake_case :Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: __UpperCamelCase = tensor_name.split('.' ) for split in splits[:-1]: __UpperCamelCase = getattr(_UpperCAmelCase , _UpperCAmelCase ) if new_module is None: raise ValueError(f'{module} has no attribute {split}.' ) __UpperCamelCase = new_module __UpperCamelCase = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f'{module} does not have a parameter or a buffer named {tensor_name}.' ) __UpperCamelCase = tensor_name in module._buffers __UpperCamelCase = getattr(_UpperCAmelCase , _UpperCAmelCase ) if old_value.device == torch.device('meta' ) and device not in ["meta", torch.device('meta' )] and value is None: raise ValueError(f'{tensor_name} is on the meta device, we need a `value` to put in on {device}.' ) __UpperCamelCase = False __UpperCamelCase = False if is_buffer or not is_bitsandbytes_available(): __UpperCamelCase = False __UpperCamelCase = False else: __UpperCamelCase = hasattr(bnb.nn , 'Params4bit' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) __UpperCamelCase = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: __UpperCamelCase = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: __UpperCamelCase = old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase , torch.Tensor ): __UpperCamelCase = value.to('cpu' ) if value.dtype == torch.inta: __UpperCamelCase = version.parse(importlib.metadata.version('bitsandbytes' ) ) > version.parse( '0.37.2' ) if not is_abit_serializable: raise ValueError( 'Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ' 'Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.' ) else: __UpperCamelCase = torch.tensor(_UpperCAmelCase , device='cpu' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , _UpperCAmelCase ) and fpaa_statistics is None: __UpperCamelCase = new_value.T __UpperCamelCase = old_value.__dict__ if is_abit: __UpperCamelCase = bnb.nn.IntaParams(_UpperCAmelCase , requires_grad=_UpperCAmelCase , **_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: __UpperCamelCase = bnb.nn.Paramsabit(_UpperCAmelCase , requires_grad=_UpperCAmelCase , **_UpperCAmelCase ).to(_UpperCAmelCase ) __UpperCamelCase = new_value if fpaa_statistics is not None: setattr(module.weight , 'SCB' , fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: __UpperCamelCase = old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase , torch.Tensor ): __UpperCamelCase = value.to(_UpperCAmelCase ) else: __UpperCamelCase = torch.tensor(_UpperCAmelCase , device=_UpperCAmelCase ) if is_buffer: __UpperCamelCase = new_value else: __UpperCamelCase = nn.Parameter(_UpperCAmelCase , requires_grad=old_value.requires_grad ) __UpperCamelCase = new_value def A ( snake_case :Tuple , snake_case :Union[str, Any]=None , snake_case :List[Any]=None , snake_case :str=None , snake_case :Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: __UpperCamelCase = [] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase , nn.Linear ) or isinstance(_UpperCAmelCase , _UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '.'.join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): __UpperCamelCase = module.weight.shape else: __UpperCamelCase = module.in_features __UpperCamelCase = module.out_features if quantization_config.quantization_method() == "llm_int8": __UpperCamelCase = bnb.nn.LinearabitLt( _UpperCAmelCase , _UpperCAmelCase , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) __UpperCamelCase = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: __UpperCamelCase = bnb.nn.Linearabit( _UpperCAmelCase , _UpperCAmelCase , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) __UpperCamelCase = True # Store the module class in case we need to transpose the weight later __UpperCamelCase = type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: __UpperCamelCase = _replace_with_bnb_linear( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , has_been_replaced=_UpperCAmelCase , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def A ( snake_case :Tuple , snake_case :int=None , snake_case :Union[str, Any]=None , snake_case :Any=None ) -> Tuple: __UpperCamelCase = ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert __UpperCamelCase = _replace_with_bnb_linear( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def A ( *snake_case :Any , **snake_case :Any ) -> str: warnings.warn( '`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead' , _UpperCAmelCase , ) return replace_with_bnb_linear(*_UpperCAmelCase , **_UpperCAmelCase ) def A ( *snake_case :str , **snake_case :Optional[int] ) -> Optional[int]: warnings.warn( '`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead' , _UpperCAmelCase , ) return set_module_quantized_tensor_to_device(*_UpperCAmelCase , **_UpperCAmelCase ) def A ( snake_case :int ) -> Union[str, Any]: __UpperCamelCase = deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() __UpperCamelCase = find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase , _UpperCAmelCase ): __UpperCamelCase = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: __UpperCamelCase = sum(_UpperCAmelCase , [] ) __UpperCamelCase = len(_UpperCAmelCase ) > 0 # Check if it is a base model __UpperCamelCase = not hasattr(_UpperCAmelCase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head __UpperCamelCase = list(model.named_children() ) __UpperCamelCase = [list_modules[-1][0]] # add last module together with tied weights __UpperCamelCase = set(_UpperCAmelCase ) - set(_UpperCAmelCase ) __UpperCamelCase = list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys __UpperCamelCase = [""".weight""", """.bias"""] __UpperCamelCase = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: __UpperCamelCase = name.replace(_UpperCAmelCase , '' ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
316
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
340
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
0
'''simple docstring''' import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _lowerCAmelCase ( __snake_case : List[Any] ) -> Union[str, Any]: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _lowerCAmelCase ( __snake_case : List[str] ) -> List[Any]: __A : List[str] = create_tensor(_UpperCAmelCase ) __A : Tuple = gather(_UpperCAmelCase ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _lowerCAmelCase ( __snake_case : Tuple ) -> Dict: __A : Any = [state.process_index] __A : List[Any] = gather_object(_UpperCAmelCase ) assert len(_UpperCAmelCase ) == state.num_processes, f'{gathered_obj}, {len(_UpperCAmelCase )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), f'{gathered_obj} != {list(range(state.num_processes ) )}' def _lowerCAmelCase ( __snake_case : Optional[Any] ) -> Tuple: __A : Any = create_tensor(_UpperCAmelCase ) __A : Tuple = broadcast(_UpperCAmelCase ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _lowerCAmelCase ( __snake_case : List[str] ) -> int: # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: __A : Dict = torch.arange(state.num_processes + 1 ).to(state.device ) else: __A : List[Any] = torch.arange(state.num_processes ).to(state.device ) __A : Tuple = pad_across_processes(_UpperCAmelCase ) 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 _lowerCAmelCase ( __snake_case : str ) -> List[str]: # For now runs on only two processes if state.num_processes != 2: return __A : Optional[Any] = create_tensor(_UpperCAmelCase ) __A : Optional[int] = reduce(_UpperCAmelCase , 'sum' ) __A : int = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase ), f'{reduced_tensor} != {truth_tensor}' def _lowerCAmelCase ( __snake_case : Optional[int] ) -> Union[str, Any]: # For now runs on only two processes if state.num_processes != 2: return __A : Tuple = create_tensor(_UpperCAmelCase ) __A : Any = reduce(_UpperCAmelCase , 'mean' ) __A : Any = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase ), f'{reduced_tensor} != {truth_tensor}' def _lowerCAmelCase ( __snake_case : Tuple ) -> Union[str, Any]: # For xla_spawn (TPUs) main() def _lowerCAmelCase ( ) -> str: __A : str = PartialState() state.print(f'State: {state}' ) state.print('testing gather' ) test_gather(_UpperCAmelCase ) state.print('testing gather_object' ) test_gather_object(_UpperCAmelCase ) state.print('testing broadcast' ) test_broadcast(_UpperCAmelCase ) state.print('testing pad_across_processes' ) test_pad_across_processes(_UpperCAmelCase ) state.print('testing reduce_sum' ) test_reduce_sum(_UpperCAmelCase ) state.print('testing reduce_mean' ) test_reduce_mean(_UpperCAmelCase ) if __name__ == "__main__": main()
190
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
124
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : Any = {'''configuration_ibert''': ['''IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''IBertConfig''', '''IBertOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : str = [ '''IBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''IBertForMaskedLM''', '''IBertForMultipleChoice''', '''IBertForQuestionAnswering''', '''IBertForSequenceClassification''', '''IBertForTokenClassification''', '''IBertModel''', '''IBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
338
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
0
def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): return base * power(_UpperCAmelCase , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print("""Raise base to the power of exponent using recursion...""") UpperCamelCase__ = int(input("""Enter the base: """).strip()) UpperCamelCase__ = int(input("""Enter the exponent: """).strip()) UpperCamelCase__ = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents UpperCamelCase__ = 1 / result print(f'''{base} to the power of {exponent} is {result}''')
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness A_ : Optional[int] = '''\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } ''' A_ : Tuple = '''\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). ''' A_ : Dict = ''' Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric("code_eval") >>> test_cases = ["assert add(2,3)==5"] >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {\'pass@1\': 0.5, \'pass@2\': 1.0} ''' A_ : int = ''' ################################################################################ !!!WARNING!!! ################################################################################ The "code_eval" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this with: >>> import os >>> os.environ["HF_ALLOW_CODE_EVAL"] = "1" ################################################################################\ ''' A_ : List[Any] = '''The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _a (datasets.Metric ): '''simple docstring''' def __A ( self ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def __A ( self , A__ , A__ , A__=[1, 10, 100] , A__=4 , A__=3.0 ): if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=A__ ) as executor: A__ : Any = [] A__ : Optional[int] = Counter() A__ : Dict = 0 A__ : Dict = defaultdict(A__ ) for task_id, (candidates, test_case) in enumerate(zip(A__ , A__ ) ): for candidate in candidates: A__ : int = candidate + """\n""" + test_case A__ : Any = (test_program, timeout, task_id, completion_id[task_id]) A__ : List[Any] = executor.submit(A__ , *A__ ) futures.append(A__ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(A__ ): A__ : Tuple = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) A__ : Optional[Any] = [], [] for result in results.values(): result.sort() A__ : Any = [r[1]["""passed"""] for r in result] total.append(len(A__ ) ) correct.append(sum(A__ ) ) A__ : Optional[Any] = np.array(A__ ) A__ : List[str] = np.array(A__ ) A__ : Any = k A__ : Tuple = {F"""pass@{k}""": estimate_pass_at_k(A__ , A__ , A__ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def UpperCamelCase (lowercase_: Any , lowercase_: Tuple , lowercase_: int ) -> Optional[int]: def estimator(lowercase_: int , lowercase_: int , lowercase_: int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): A__ : Tuple = itertools.repeat(_UpperCAmelCase , len(_UpperCAmelCase ) ) else: assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ) A__ : List[Any] = iter(_UpperCAmelCase ) return np.array([estimator(int(_UpperCAmelCase ) , int(_UpperCAmelCase ) , _UpperCAmelCase ) for n, c in zip(_UpperCAmelCase , _UpperCAmelCase )] )
192
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
0
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def A_ ( _lowerCAmelCase ) -> List[str]: if "model" in orig_key: UpperCamelCase : str = orig_key.replace("model." , "" ) if "norm1" in orig_key: UpperCamelCase : List[str] = orig_key.replace("norm1" , "attention.output.LayerNorm" ) if "norm2" in orig_key: UpperCamelCase : int = orig_key.replace("norm2" , "output.LayerNorm" ) if "norm" in orig_key: UpperCamelCase : List[Any] = orig_key.replace("norm" , "LayerNorm" ) if "transformer" in orig_key: UpperCamelCase : Optional[int] = orig_key.split("." )[0].split("_" )[-1] UpperCamelCase : Dict = orig_key.replace(F"""transformer_{layer_num}""" , F"""encoder.layer.{layer_num}""" ) if "mha.attn" in orig_key: UpperCamelCase : int = orig_key.replace("mha.attn" , "attention.self" ) if "mha" in orig_key: UpperCamelCase : Any = orig_key.replace("mha" , "attention" ) if "W_q" in orig_key: UpperCamelCase : Optional[Any] = orig_key.replace("W_q" , "self.query" ) if "W_k" in orig_key: UpperCamelCase : Any = orig_key.replace("W_k" , "self.key" ) if "W_v" in orig_key: UpperCamelCase : Tuple = orig_key.replace("W_v" , "self.value" ) if "ff1" in orig_key: UpperCamelCase : List[Any] = orig_key.replace("ff1" , "intermediate.dense" ) if "ff2" in orig_key: UpperCamelCase : str = orig_key.replace("ff2" , "output.dense" ) if "ff" in orig_key: UpperCamelCase : int = orig_key.replace("ff" , "output.dense" ) if "mlm_class" in orig_key: UpperCamelCase : Optional[int] = orig_key.replace("mlm.mlm_class" , "cls.predictions.decoder" ) if "mlm" in orig_key: UpperCamelCase : Dict = orig_key.replace("mlm" , "cls.predictions.transform" ) if "cls" not in orig_key: UpperCamelCase : int = """yoso.""" + orig_key return orig_key def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Dict: for key in orig_state_dict.copy().keys(): UpperCamelCase : Union[str, Any] = orig_state_dict.pop(_UpperCAmelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: UpperCamelCase : Optional[int] = val UpperCamelCase : Optional[int] = orig_state_dict["""cls.predictions.decoder.bias"""] UpperCamelCase : Optional[Any] = torch.arange(_UpperCAmelCase ).expand((1, -1) ) + 2 return orig_state_dict def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: UpperCamelCase : Any = torch.load(_UpperCAmelCase , map_location="cpu" )["""model_state_dict"""] UpperCamelCase : List[str] = YosoConfig.from_json_file(_UpperCAmelCase ) UpperCamelCase : Union[str, Any] = YosoForMaskedLM(_UpperCAmelCase ) UpperCamelCase : Union[str, Any] = convert_checkpoint_helper(config.max_position_embeddings , _UpperCAmelCase ) print(model.load_state_dict(_UpperCAmelCase ) ) model.eval() model.save_pretrained(_UpperCAmelCase ) print(F"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) if __name__ == "__main__": __lowerCamelCase : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--pytorch_model_path""", default=None, type=str, required=True, help="""Path to YOSO pytorch checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The json file for YOSO model config.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __lowerCamelCase : List[str] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
52
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
0
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" , [ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase , i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] , snake_case__ : Dict ): """simple docstring""" _snake_case : Tuple = _distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" , [ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] , ) def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : List[Any] , snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case : List[str] = _split_gen_kwargs(_UpperCAmelCase , _UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" , [ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : List[Any] ): """simple docstring""" if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _snake_case : Dict = _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
64
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''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 __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
0
"""simple docstring""" from collections.abc import Generator from math import sin def __lowercase ( _a ): if len(_UpperCAmelCase ) != 32: raise ValueError('''Input must be of length 32''' ) snake_case_ : Union[str, Any] = B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def __lowercase ( _a ): if i < 0: raise ValueError('''Input must be non-negative''' ) snake_case_ : Dict = format(_UpperCAmelCase , '''08x''' )[-8:] snake_case_ : Optional[Any] = B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' ) return little_endian_hex def __lowercase ( _a ): snake_case_ : Tuple = B"""""" for char in message: bit_string += format(_UpperCAmelCase , '''08b''' ).encode('''utf-8''' ) snake_case_ : Optional[Any] = format(len(_UpperCAmelCase ) , '''064b''' ).encode('''utf-8''' ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_UpperCAmelCase ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def __lowercase ( _a ): if len(_UpperCAmelCase ) % 512 != 0: raise ValueError('''Input must have length that\'s a multiple of 512''' ) for pos in range(0 , len(_UpperCAmelCase ) , 512 ): snake_case_ : Optional[Any] = bit_string[pos : pos + 512] snake_case_ : Any = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def __lowercase ( _a ): if i < 0: raise ValueError('''Input must be non-negative''' ) snake_case_ : Any = format(_UpperCAmelCase , '''032b''' ) snake_case_ : str = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(_UpperCAmelCase , 2 ) def __lowercase ( _a , _a ): return (a + b) % 2**32 def __lowercase ( _a , _a ): if i < 0: raise ValueError('''Input must be non-negative''' ) if shift < 0: raise ValueError('''Shift must be non-negative''' ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def __lowercase ( _a ): snake_case_ : List[str] = preprocess(_UpperCAmelCase ) snake_case_ : Optional[int] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states snake_case_ : Union[str, Any] = 0x6745_2301 snake_case_ : List[Any] = 0xefcd_ab89 snake_case_ : int = 0x98ba_dcfe snake_case_ : List[str] = 0x1032_5476 snake_case_ : List[Any] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_UpperCAmelCase ): snake_case_ : str = aa snake_case_ : str = ba snake_case_ : Optional[int] = ca snake_case_ : List[str] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f snake_case_ : Optional[int] = d ^ (b & (c ^ d)) snake_case_ : Dict = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f snake_case_ : Optional[Any] = c ^ (d & (b ^ c)) snake_case_ : List[Any] = (5 * i + 1) % 16 elif i <= 47: snake_case_ : Union[str, Any] = b ^ c ^ d snake_case_ : Union[str, Any] = (3 * i + 5) % 16 else: snake_case_ : Any = c ^ (b | not_aa(_UpperCAmelCase )) snake_case_ : Optional[Any] = (7 * i) % 16 snake_case_ : Tuple = (f + a + added_consts[i] + block_words[g]) % 2**32 snake_case_ : List[Any] = d snake_case_ : List[str] = c snake_case_ : int = b snake_case_ : int = sum_aa(_UpperCAmelCase , left_rotate_aa(_UpperCAmelCase , shift_amounts[i] ) ) # Add hashed chunk to running total snake_case_ : int = sum_aa(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : Dict = sum_aa(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : Dict = sum_aa(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : Any = sum_aa(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ : Any = reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) return digest if __name__ == "__main__": import doctest doctest.testmod()
264
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
0
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _A ( _lowercase , _lowercase ) -> Any: """simple docstring""" __UpperCamelCase = [] for part_id in partition_order: __UpperCamelCase = df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(_UpperCAmelCase ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(1_00 ).repartition(1 ) __UpperCamelCase = Spark(_UpperCAmelCase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> str: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(10 ).repartition(2 ) __UpperCamelCase = [1, 0] __UpperCamelCase = _generate_iterable_examples(_UpperCAmelCase , _UpperCAmelCase ) # Reverse the partitions. __UpperCamelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase , _UpperCAmelCase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): __UpperCamelCase = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> int: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(10 ).repartition(1 ) __UpperCamelCase = SparkExamplesIterable(_UpperCAmelCase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> Tuple: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('numpy.random.Generator' ) as generator_mock: __UpperCamelCase = lambda _lowercase : x.reverse() __UpperCamelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase , [2, 1, 0] ) __UpperCamelCase = SparkExamplesIterable(_UpperCAmelCase ).shuffle_data_sources(_UpperCAmelCase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): __UpperCamelCase = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> List[str]: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 __UpperCamelCase = SparkExamplesIterable(_UpperCAmelCase ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 __UpperCamelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase , [0, 2] ) for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): __UpperCamelCase = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 __UpperCamelCase = SparkExamplesIterable(_UpperCAmelCase ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 __UpperCamelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase , [1, 3] ) for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): __UpperCamelCase = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _A ( ) -> Tuple: """simple docstring""" __UpperCamelCase = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __UpperCamelCase = spark.range(1_00 ).repartition(1 ) __UpperCamelCase = Spark(_UpperCAmelCase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
310
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( """features""" ,[ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : Dict = logging.get_logger(__name__) UpperCamelCase : int = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class __lowerCAmelCase ( UpperCAmelCase__ ): lowercase = "biogpt" def __init__( self , __UpperCAmelCase=4_2384 , __UpperCAmelCase=1024 , __UpperCAmelCase=24 , __UpperCAmelCase=16 , __UpperCAmelCase=4096 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=1024 , __UpperCAmelCase=0.0_2 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=2 , **__UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = vocab_size __UpperCamelCase = max_position_embeddings __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = initializer_range __UpperCamelCase = layer_norm_eps __UpperCamelCase = scale_embedding __UpperCamelCase = use_cache __UpperCamelCase = layerdrop __UpperCamelCase = activation_dropout super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
316
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
0
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCAmelCase__, unittest.TestCase ): a_ =LxmertTokenizer a_ =LxmertTokenizerFast a_ =True a_ =True def UpperCAmelCase ( self )-> List[str]: '''simple docstring''' super().setUp() lowerCAmelCase__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCAmelCase ( self , __UpperCAmelCase )-> Tuple: '''simple docstring''' lowerCAmelCase__ = """UNwant\u00E9d,running""" lowerCAmelCase__ = """unwanted, running""" return input_text, output_text def UpperCAmelCase ( self )-> List[Any]: '''simple docstring''' lowerCAmelCase__ = self.tokenizer_class(self.vocab_file ) lowerCAmelCase__ = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(__UpperCAmelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [7, 4, 5, 10, 8, 9] ) def UpperCAmelCase ( self )-> int: '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = """I was born in 92000, and this is falsé.""" lowerCAmelCase__ = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
340
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( 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 A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ : List[Any] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
190
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
0
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __lowercase (unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase ( self ) -> Optional[Any]: torch.manual_seed(0 ) snake_case : str = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase ( self ) -> Union[str, Any]: snake_case : Any = self.dummy_uncond_unet snake_case : Optional[Any] = ScoreSdeVeScheduler() snake_case : Tuple = ScoreSdeVePipeline(unet=A , scheduler=A ) sde_ve.to(A ) sde_ve.set_progress_bar_config(disable=A ) snake_case : Union[str, Any] = torch.manual_seed(0 ) snake_case : Tuple = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=A ).images snake_case : Dict = torch.manual_seed(0 ) snake_case : Tuple = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=A , return_dict=A )[ 0 ] snake_case : Any = image[0, -3:, -3:, -1] snake_case : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) snake_case : Any = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __lowercase (unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: snake_case : List[str] = """google/ncsnpp-church-256""" snake_case : Optional[int] = UNetaDModel.from_pretrained(A ) snake_case : Union[str, Any] = ScoreSdeVeScheduler.from_pretrained(A ) snake_case : Optional[Any] = ScoreSdeVePipeline(unet=A , scheduler=A ) sde_ve.to(A ) sde_ve.set_progress_bar_config(disable=A ) snake_case : int = torch.manual_seed(0 ) snake_case : Optional[int] = sde_ve(num_inference_steps=1_0 , output_type="""numpy""" , generator=A ).images snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) snake_case : str = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
124
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
0
import sys from collections import defaultdict class lowercase_ : """simple docstring""" def __init__( self ) ->List[str]: lowerCAmelCase = [] def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE ) ->Union[str, Any]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->str: lowerCAmelCase = pos def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->Optional[int]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase = 2 * start + 1 else: lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase = heap[smallest_child], positions[smallest_child] lowerCAmelCase = ( heap[start], positions[start], ) lowerCAmelCase = temp, tempa lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __SCREAMING_SNAKE_CASE ) self.top_to_bottom(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->Dict: lowerCAmelCase = position[index] while index != 0: lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase = heap[parent] lowerCAmelCase = position[parent] self.set_position(position[parent] , __SCREAMING_SNAKE_CASE ) else: lowerCAmelCase = val lowerCAmelCase = temp self.set_position(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) break lowerCAmelCase = parent else: lowerCAmelCase = val lowerCAmelCase = temp self.set_position(__SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->List[str]: lowerCAmelCase = len(__SCREAMING_SNAKE_CASE ) // 2 - 1 for i in range(__SCREAMING_SNAKE_CASE , -1 , -1 ): self.top_to_bottom(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->Optional[Any]: lowerCAmelCase = positions[0] lowerCAmelCase = sys.maxsize self.top_to_bottom(__SCREAMING_SNAKE_CASE , 0 , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) return temp def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> List[str]: lowerCAmelCase = Heap() lowerCAmelCase = [0] * len(_UpperCAmelCase ) lowerCAmelCase = [-1] * len(_UpperCAmelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase = [] for vertex in range(len(_UpperCAmelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCAmelCase ) heap.node_position.append(_UpperCAmelCase ) lowerCAmelCase = [] lowerCAmelCase = 1 lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase = 0 lowerCAmelCase = distance heap.heapify(_UpperCAmelCase , _UpperCAmelCase ) for _ in range(1 , len(_UpperCAmelCase ) ): lowerCAmelCase = heap.delete_minimum(_UpperCAmelCase , _UpperCAmelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCAmelCase )] ): lowerCAmelCase = distance heap.bottom_to_top( _UpperCAmelCase , heap.get_position(_UpperCAmelCase ) , _UpperCAmelCase , _UpperCAmelCase ) lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > lowercase__ : List[str] = int(input('''Enter number of edges: ''').strip()) lowercase__ : List[Any] = defaultdict(list) for _ in range(edges_number): lowercase__ : Union[str, Any] = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
338
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class a__ ( unittest.TestCase ): def __init__( self , _A , _A=7 , _A=3 , _A=3_0 , _A=4_0_0 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 2_5_5 , _A=True , ): """simple docstring""" __lowerCAmelCase = size if size is not None else {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = num_channels __lowerCAmelCase = min_resolution __lowerCAmelCase = max_resolution __lowerCAmelCase = do_resize __lowerCAmelCase = size __lowerCAmelCase = do_normalize __lowerCAmelCase = image_mean __lowerCAmelCase = image_std __lowerCAmelCase = do_rescale __lowerCAmelCase = rescale_factor __lowerCAmelCase = do_pad def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __SCREAMING_SNAKE_CASE( self , _A , _A=False ): """simple docstring""" if not batched: __lowerCAmelCase = image_inputs[0] if isinstance(_A , Image.Image ): __lowerCAmelCase = image.size else: __lowerCAmelCase = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase = int(self.size["shortest_edge"] * h / w ) __lowerCAmelCase = self.size["""shortest_edge"""] elif w > h: __lowerCAmelCase = self.size["""shortest_edge"""] __lowerCAmelCase = int(self.size["shortest_edge"] * w / h ) else: __lowerCAmelCase = self.size["""shortest_edge"""] __lowerCAmelCase = self.size["""shortest_edge"""] else: __lowerCAmelCase = [] for image in image_inputs: __lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase = max(_A , key=lambda _A : item[0] )[0] __lowerCAmelCase = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a__ ( UpperCAmelCase__ , unittest.TestCase ): _a : List[str] = YolosImageProcessor if is_vision_available() else None def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = YolosImageProcessingTester(self ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , "image_mean" ) ) self.assertTrue(hasattr(_A , "image_std" ) ) self.assertTrue(hasattr(_A , "do_normalize" ) ) self.assertTrue(hasattr(_A , "do_resize" ) ) self.assertTrue(hasattr(_A , "size" ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _A ) __lowerCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A , batched=_A ) __lowerCAmelCase = image_processing(_A , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(_A , return_tensors="pt" ).pixel_values __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase = 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 __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(_A , return_tensors="pt" ).pixel_values __lowerCAmelCase = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCAmelCase = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __lowerCAmelCase = image_processing_a.pad(_A , return_tensors="pt" ) __lowerCAmelCase = image_processing_a(_A , return_tensors="pt" ) self.assertTrue( torch.allclose(encoded_images_with_method["pixel_values"] , encoded_images["pixel_values"] , atol=1E-4 ) ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __lowerCAmelCase = json.loads(f.read() ) __lowerCAmelCase = {"""image_id""": 3_9_7_6_9, """annotations""": target} # encode them __lowerCAmelCase = YolosImageProcessor.from_pretrained("hustvl/yolos-small" ) __lowerCAmelCase = image_processing(images=_A , annotations=_A , return_tensors="pt" ) # verify pixel values __lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , _A ) __lowerCAmelCase = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _A , atol=1E-4 ) ) # verify area __lowerCAmelCase = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _A ) ) # verify boxes __lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _A ) __lowerCAmelCase = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _A , atol=1E-3 ) ) # verify image_id __lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _A ) ) # verify is_crowd __lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _A ) ) # verify class_labels __lowerCAmelCase = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _A ) ) # verify orig_size __lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _A ) ) # verify size __lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _A ) ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __lowerCAmelCase = json.loads(f.read() ) __lowerCAmelCase = {"""file_name""": """000000039769.png""", """image_id""": 3_9_7_6_9, """segments_info""": target} __lowerCAmelCase = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __lowerCAmelCase = YolosImageProcessor(format="coco_panoptic" ) __lowerCAmelCase = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors="pt" ) # verify pixel values __lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , _A ) __lowerCAmelCase = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _A , atol=1E-4 ) ) # verify area __lowerCAmelCase = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _A ) ) # verify boxes __lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _A ) __lowerCAmelCase = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _A , atol=1E-3 ) ) # verify image_id __lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _A ) ) # verify is_crowd __lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _A ) ) # verify class_labels __lowerCAmelCase = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _A ) ) # verify masks __lowerCAmelCase = 8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , _A ) # verify orig_size __lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _A ) ) # verify size __lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _A ) )
92
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
0
import os import re import shutil import sys import tempfile import unittest import black A_ : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. A_ : Union[str, Any] = ''' def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states ''' class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): A__ : str = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) A__ : Optional[Any] = self.transformer_dir shutil.copy( os.path.join(A__ , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def __A ( self ): A__ : Optional[Any] = """src/transformers""" shutil.rmtree(self.transformer_dir ) def __A ( self , A__ , A__ , A__ , A__=None ): A__ : List[Any] = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: A__ : Any = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) A__ : List[Any] = black.format_str(A__ , mode=A__ ) A__ : Optional[int] = os.path.join(self.transformer_dir , """new_code.py""" ) with open(A__ , """w""" , newline="""\n""" ) as f: f.write(A__ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(A__ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=A__ ) with open(A__ , """r""" ) as f: self.assertTrue(f.read() , A__ ) def __A ( self ): A__ : Dict = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(A__ , A__ ) def __A ( self ): self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , A__ , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , A__ ) , ) # Copy consistency with a really long name A__ : int = """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( F"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , F"""{long_class_name}LMPredictionHead""" , re.sub("""Bert""" , A__ , A__ ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , A__ , overwrite_result=re.sub("""Bert""" , """TestModel""" , A__ ) , ) def __A ( self ): A__ : List[Any] = check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] A__ : Tuple = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) A__ : Union[str, Any] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ : Optional[int] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) A__ : Union[str, Any] = check_copies.convert_to_localized_md( A__ , A__ , localized_readme["""format_model_list"""] ) self.assertFalse(A__ ) self.assertEqual(A__ , A__ ) A__ : List[str] = check_copies.convert_to_localized_md( A__ , A__ , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(A__ ) A__ : Dict = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) A__ : Tuple = ( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ : Optional[Any] = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) A__ : Union[str, Any] = check_copies.convert_to_localized_md( A__ , A__ , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(A__ , A__ )
192
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Dict = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class A__ ( UpperCAmelCase__ ): _UpperCAmelCase :Tuple = "realm" def __init__( self , A_=3_0522 , A_=768 , A_=128 , A_=12 , A_=12 , A_=8 , A_=3072 , A_="gelu_new" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=256 , A_=10 , A_=1e-3 , A_=5 , A_=320 , A_=1335_3718 , A_=5000 , A_=1 , A_=0 , A_=2 , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) # Common config UpperCamelCase : Tuple = vocab_size UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : List[Any] = hidden_size UpperCamelCase : Any = retriever_proj_size UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : int = num_attention_heads UpperCamelCase : Optional[Any] = num_candidates UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : Any = attention_probs_dropout_prob UpperCamelCase : Optional[Any] = initializer_range UpperCamelCase : List[str] = type_vocab_size UpperCamelCase : str = layer_norm_eps # Reader config UpperCamelCase : Tuple = span_hidden_size UpperCamelCase : List[Any] = max_span_width UpperCamelCase : Optional[Any] = reader_layer_norm_eps UpperCamelCase : int = reader_beam_size UpperCamelCase : Tuple = reader_seq_len # Retrieval config UpperCamelCase : Optional[Any] = num_block_records UpperCamelCase : Any = searcher_beam_size
52
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
0
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ): """simple docstring""" if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) _snake_case : Dict = str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b" _snake_case : Tuple = str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b" _snake_case : Dict = max(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) ) return "0b" + "".join( str(int(char_a == """1""" and char_b == """1""" ) ) for char_a, char_b in zip(a_binary.zfill(_UpperCAmelCase ) , b_binary.zfill(_UpperCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
64
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
0
"""simple docstring""" from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function lowercase__ : str = 1.0_5457_1817e-34 # unit of ℏ : J * s lowercase__ : int = 3e8 # unit of c : m * s^-1 def __lowercase ( _a , _a , _a ): if (force, area, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if force < 0: raise ValueError('''Magnitude of force can not be negative''' ) if distance < 0: raise ValueError('''Distance can not be negative''' ) if area < 0: raise ValueError('''Area can not be negative''' ) if force == 0: snake_case_ : Optional[int] = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: snake_case_ : Optional[Any] = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: snake_case_ : Union[str, Any] = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('''One and only one argument must be 0''' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
264
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
0
def _A ( _lowercase = 1_00 ) -> int: """simple docstring""" __UpperCamelCase = n * (n + 1) * (2 * n + 1) / 6 __UpperCamelCase = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
310
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCamelCase : Optional[Any] = logging.get_logger(__name__) UpperCamelCase : Tuple = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase : List[Any] = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCamelCase : Optional[Any] = { '''bert-base-uncased''': 5_1_2, '''bert-large-uncased''': 5_1_2, '''bert-base-cased''': 5_1_2, '''bert-large-cased''': 5_1_2, '''bert-base-multilingual-uncased''': 5_1_2, '''bert-base-multilingual-cased''': 5_1_2, '''bert-base-chinese''': 5_1_2, '''bert-base-german-cased''': 5_1_2, '''bert-large-uncased-whole-word-masking''': 5_1_2, '''bert-large-cased-whole-word-masking''': 5_1_2, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_1_2, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_1_2, '''bert-base-cased-finetuned-mrpc''': 5_1_2, '''bert-base-german-dbmdz-cased''': 5_1_2, '''bert-base-german-dbmdz-uncased''': 5_1_2, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_1_2, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_1_2, '''wietsedv/bert-base-dutch-cased''': 5_1_2, } UpperCamelCase : List[str] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class __lowerCAmelCase ( UpperCAmelCase__ ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_INIT_CONFIGURATION lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = BertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('strip_accents' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __UpperCAmelCase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(__UpperCAmelCase , normalizer_state.pop('type' ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**__UpperCAmelCase ) __UpperCamelCase = do_lower_case def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __UpperCamelCase = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
316
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
0
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _a ( UpperCamelCase_ : Any , UpperCamelCase_ : str ) -> Dict: """simple docstring""" assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def _a ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str ) -> Optional[Any]: """simple docstring""" lowerCAmelCase__ = tmp_path / """cache""" lowerCAmelCase__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCAmelCase__ = SqlDatasetReader( "dataset" , "sqlite:///" + sqlite_path , cache_dir=_UpperCAmelCase , keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase , _UpperCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def _a ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int ) -> List[Any]: """simple docstring""" lowerCAmelCase__ = tmp_path / """cache""" lowerCAmelCase__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} lowerCAmelCase__ = features.copy() if features else default_expected_features lowerCAmelCase__ = ( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase__ = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , features=_UpperCAmelCase , cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase , _UpperCAmelCase ) def _a ( UpperCamelCase_ : Optional[Any] ) -> List[str]: """simple docstring""" with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: lowerCAmelCase__ = con.cursor() cur.execute("SELECT * FROM dataset" ) for row in cur: yield row @require_sqlalchemy def _a ( UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ = tmp_path / """cache""" lowerCAmelCase__ = os.path.join(_UpperCAmelCase , "tmp.sql" ) lowerCAmelCase__ = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=1 ).write() lowerCAmelCase__ = iter_sql_file(_UpperCAmelCase ) lowerCAmelCase__ = iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase , _UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def _a ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Any , UpperCamelCase_ : List[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ = tmp_path / """cache""" lowerCAmelCase__ = os.path.join(_UpperCAmelCase , "tmp.sql" ) lowerCAmelCase__ = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=2 ).write() lowerCAmelCase__ = iter_sql_file(_UpperCAmelCase ) lowerCAmelCase__ = iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase , _UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def _a ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : List[Any] ) -> List[str]: """simple docstring""" lowerCAmelCase__ = tmp_path / """cache""" lowerCAmelCase__ = os.path.join(_UpperCAmelCase , "tmp.sql" ) lowerCAmelCase__ = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=0 ).write()
340
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
0
'''simple docstring''' def _lowerCAmelCase ( __snake_case : int = 1_00 ) -> int: __A : Dict = set() __A : str = 0 __A : List[str] = n + 1 # maximum limit for a in range(2 , _UpperCAmelCase ): for b in range(2 , _UpperCAmelCase ): __A : Optional[int] = a**b # calculates the current power collect_powers.add(_UpperCAmelCase ) # adds the result to the set return len(_UpperCAmelCase ) if __name__ == "__main__": print('''Number of terms ''', solution(int(str(input()).strip())))
190
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCamelCase : List[str] = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
124
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
from __future__ import annotations class lowercase_ : """simple docstring""" def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ->Optional[int]: lowerCAmelCase = text, pattern lowerCAmelCase = len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE ) ->int: for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE ) ->int: 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 SCREAMING_SNAKE_CASE_ ( self ) ->list[int]: lowerCAmelCase = [] for i in range(self.textLen - self.patLen + 1 ): lowerCAmelCase = self.mismatch_in_text(__SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(__SCREAMING_SNAKE_CASE ) else: lowerCAmelCase = self.match_in_pattern(self.text[mismatch_index] ) lowerCAmelCase = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions lowercase__ : Any = '''ABAABA''' lowercase__ : int = '''AB''' lowercase__ : Optional[int] = BoyerMooreSearch(text, pattern) lowercase__ : Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
338
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
0
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( 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 UpperCamelCase__ = logging.get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] ): 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 ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : Optional[str] , SCREAMING_SNAKE_CASE_ : Optional[str] = None ): __lowerCAmelCase = tesseract_config if tesseract_config is not None else """""" # apply OCR __lowerCAmelCase = to_pil_image(_UpperCAmelCase ) __lowerCAmelCase = pil_image.size __lowerCAmelCase = pytesseract.image_to_data(_UpperCAmelCase , lang=_UpperCAmelCase , output_type="dict" , config=_UpperCAmelCase ) __lowerCAmelCase = data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates __lowerCAmelCase = [idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] __lowerCAmelCase = [word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __lowerCAmelCase = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __lowerCAmelCase = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __lowerCAmelCase = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __lowerCAmelCase = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format __lowerCAmelCase = [] for x, y, w, h in zip(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): __lowerCAmelCase = [x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes __lowerCAmelCase = [] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a__ ( UpperCAmelCase__ ): _a : List[Any] = ["pixel_values"] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = None , _A = "" , **_A , ): """simple docstring""" super().__init__(**_A ) __lowerCAmelCase = size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} __lowerCAmelCase = get_size_dict(_A ) __lowerCAmelCase = do_resize __lowerCAmelCase = size __lowerCAmelCase = resample __lowerCAmelCase = apply_ocr __lowerCAmelCase = ocr_lang __lowerCAmelCase = tesseract_config def __SCREAMING_SNAKE_CASE( self , _A , _A , _A = PILImageResampling.BILINEAR , _A = None , **_A , ): """simple docstring""" __lowerCAmelCase = 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()}""" ) __lowerCAmelCase = (size["""height"""], size["""width"""]) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ): """simple docstring""" __lowerCAmelCase = do_resize if do_resize is not None else self.do_resize __lowerCAmelCase = size if size is not None else self.size __lowerCAmelCase = get_size_dict(_A ) __lowerCAmelCase = resample if resample is not None else self.resample __lowerCAmelCase = apply_ocr if apply_ocr is not None else self.apply_ocr __lowerCAmelCase = ocr_lang if ocr_lang is not None else self.ocr_lang __lowerCAmelCase = tesseract_config if tesseract_config is not None else self.tesseract_config __lowerCAmelCase = 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." ) # All transformations expect numpy arrays. __lowerCAmelCase = [to_numpy_array(_A ) for image in images] if apply_ocr: requires_backends(self , "pytesseract" ) __lowerCAmelCase = [] __lowerCAmelCase = [] for image in images: __lowerCAmelCase = apply_tesseract(_A , _A , _A ) words_batch.append(_A ) boxes_batch.append(_A ) if do_resize: __lowerCAmelCase = [self.resize(image=_A , size=_A , resample=_A ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) __lowerCAmelCase = [flip_channel_order(_A ) for image in images] __lowerCAmelCase = [to_channel_dimension_format(_A , _A ) for image in images] __lowerCAmelCase = BatchFeature(data={"pixel_values": images} , tensor_type=_A ) if apply_ocr: __lowerCAmelCase = words_batch __lowerCAmelCase = boxes_batch return data
92
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
0
def UpperCamelCase (lowercase_: float , lowercase_: list[float] ) -> float: if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be empty""" ) A__ : Optional[int] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_UpperCAmelCase ) ) return round(_UpperCAmelCase , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
192
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Dict = logging.get_logger(__name__) __lowerCamelCase : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class A__ ( UpperCAmelCase__ ): _UpperCAmelCase :List[Any] = "vivit" def __init__( self , A_=224 , A_=32 , A_=[2, 16, 16] , A_=3 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu_fast" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1e-06 , A_=True , **A_ , ): '''simple docstring''' UpperCamelCase : Optional[Any] = hidden_size UpperCamelCase : Dict = num_hidden_layers UpperCamelCase : List[str] = num_attention_heads UpperCamelCase : Tuple = intermediate_size UpperCamelCase : Any = hidden_act UpperCamelCase : Any = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[str] = initializer_range UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : List[Any] = image_size UpperCamelCase : int = num_frames UpperCamelCase : Any = tubelet_size UpperCamelCase : Optional[int] = num_channels UpperCamelCase : List[Any] = qkv_bias super().__init__(**A_ )
52
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ = logging.get_logger(__name__) class lowercase( UpperCAmelCase__ ): '''simple docstring''' def __init__( self: Optional[int], *a_: int, **a_: str ): '''simple docstring''' warnings.warn( """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use CLIPImageProcessor instead.""", a_, ) super().__init__(*a_, **a_ )
64
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''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 __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
0
"""simple docstring""" import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowercase__ : List[str] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '''--original_config_file''', default=None, type=str, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--scheduler_type''', default='''pndm''', type=str, help='''Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']''', ) parser.add_argument( '''--pipeline_type''', default=None, type=str, help=( '''The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'''' '''. If `None` pipeline will be automatically inferred.''' ), ) parser.add_argument( '''--image_size''', default=None, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--prediction_type''', default=None, type=str, help=( '''The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable''' ''' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') parser.add_argument( '''--stable_unclip''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.''', ) parser.add_argument( '''--stable_unclip_prior''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.''', ) parser.add_argument( '''--clip_stats_path''', type=str, help='''Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.''', required=False, ) parser.add_argument( '''--controlnet''', action='''store_true''', default=None, help='''Set flag if this is a controlnet checkpoint.''' ) parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--vae_path''', type=str, default=None, required=False, help='''Set to a path, hub id to an already converted vae to not convert it again.''', ) lowercase__ : Optional[int] = parser.parse_args() lowercase__ : Dict = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
264
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
0
class __lowerCamelCase : def __init__( self: List[str] ): '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = 0 __UpperCamelCase = {} def snake_case_ ( self: Any,A_: List[str] ): '''simple docstring''' if vertex not in self.adjacency: __UpperCamelCase = {} self.num_vertices += 1 def snake_case_ ( self: Optional[Any],A_: str,A_: str,A_: Any ): '''simple docstring''' self.add_vertex(A_ ) self.add_vertex(A_ ) if head == tail: return __UpperCamelCase = weight __UpperCamelCase = weight def snake_case_ ( self: Dict ): '''simple docstring''' __UpperCamelCase = self.get_edges() for edge in edges: __UpperCamelCase = edge edges.remove((tail, head, weight) ) for i in range(len(A_ ) ): __UpperCamelCase = list(edges[i] ) edges.sort(key=lambda A_ : e[2] ) for i in range(len(A_ ) - 1 ): if edges[i][2] >= edges[i + 1][2]: __UpperCamelCase = edges[i][2] + 1 for edge in edges: __UpperCamelCase = edge __UpperCamelCase = weight __UpperCamelCase = weight def __str__( self: int ): '''simple docstring''' __UpperCamelCase = """""" for tail in self.adjacency: for head in self.adjacency[tail]: __UpperCamelCase = self.adjacency[head][tail] string += F'''{head} -> {tail} == {weight}\n''' return string.rstrip('\n' ) def snake_case_ ( self: Optional[int] ): '''simple docstring''' __UpperCamelCase = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def snake_case_ ( self: List[Any] ): '''simple docstring''' return self.adjacency.keys() @staticmethod def snake_case_ ( A_: Dict=None,A_: List[Any]=None ): '''simple docstring''' __UpperCamelCase = Graph() if vertices is None: __UpperCamelCase = [] if edges is None: __UpperCamelCase = [] for vertex in vertices: g.add_vertex(A_ ) for edge in edges: g.add_edge(*A_ ) return g class __lowerCamelCase : def __init__( self: Optional[int] ): '''simple docstring''' __UpperCamelCase = {} __UpperCamelCase = {} def __len__( self: List[Any] ): '''simple docstring''' return len(self.parent ) def snake_case_ ( self: Tuple,A_: Tuple ): '''simple docstring''' if item in self.parent: return self.find(A_ ) __UpperCamelCase = item __UpperCamelCase = 0 return item def snake_case_ ( self: int,A_: Dict ): '''simple docstring''' if item not in self.parent: return self.make_set(A_ ) if item != self.parent[item]: __UpperCamelCase = self.find(self.parent[item] ) return self.parent[item] def snake_case_ ( self: Optional[int],A_: Tuple,A_: List[Any] ): '''simple docstring''' __UpperCamelCase = self.find(A_ ) __UpperCamelCase = self.find(A_ ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: __UpperCamelCase = roota return roota if self.rank[roota] < self.rank[roota]: __UpperCamelCase = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 __UpperCamelCase = roota return roota return None @staticmethod def snake_case_ ( A_: Dict ): '''simple docstring''' __UpperCamelCase = graph.num_vertices __UpperCamelCase = Graph.UnionFind() __UpperCamelCase = [] while num_components > 1: __UpperCamelCase = {} for vertex in graph.get_vertices(): __UpperCamelCase = -1 __UpperCamelCase = graph.get_edges() for edge in edges: __UpperCamelCase = edge edges.remove((tail, head, weight) ) for edge in edges: __UpperCamelCase = edge __UpperCamelCase = union_find.find(A_ ) __UpperCamelCase = union_find.find(A_ ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __UpperCamelCase = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __UpperCamelCase = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: __UpperCamelCase = cheap_edge[vertex] if union_find.find(A_ ) != union_find.find(A_ ): union_find.union(A_,A_ ) mst_edges.append(cheap_edge[vertex] ) __UpperCamelCase = num_components - 1 __UpperCamelCase = Graph.build(edges=A_ ) return mst
310
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( """features""" ,[ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : int = logging.get_logger(__name__) UpperCamelCase : Optional[int] = { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/config.json''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/config.json''', '''funnel-transformer/medium-base''': '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json''', '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/config.json''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json''', '''funnel-transformer/xlarge-base''': '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json''', } class __lowerCAmelCase ( UpperCAmelCase__ ): lowercase = "funnel" lowercase = { "hidden_size": "d_model", "num_attention_heads": "n_head", } def __init__( self , __UpperCAmelCase=3_0522 , __UpperCAmelCase=[4, 4, 4] , __UpperCAmelCase=None , __UpperCAmelCase=2 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=64 , __UpperCAmelCase=3072 , __UpperCAmelCase="gelu_new" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=None , __UpperCAmelCase=1E-9 , __UpperCAmelCase="mean" , __UpperCAmelCase="relative_shift" , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = vocab_size __UpperCamelCase = block_sizes __UpperCamelCase = [1] * len(__UpperCAmelCase ) if block_repeats is None else block_repeats assert len(__UpperCAmelCase ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." __UpperCamelCase = num_decoder_layers __UpperCamelCase = d_model __UpperCamelCase = n_head __UpperCamelCase = d_head __UpperCamelCase = d_inner __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout __UpperCamelCase = attention_dropout __UpperCamelCase = activation_dropout __UpperCamelCase = initializer_range __UpperCamelCase = initializer_std __UpperCamelCase = layer_norm_eps assert pooling_type in [ "mean", "max", ], F'Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.' __UpperCamelCase = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F'Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.' __UpperCamelCase = attention_type __UpperCamelCase = separate_cls __UpperCamelCase = truncate_seq __UpperCamelCase = pool_q_only super().__init__(**__UpperCAmelCase ) @property def UpperCAmelCase ( self ): '''simple docstring''' return sum(self.block_sizes ) @num_hidden_layers.setter def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.' ) @property def UpperCAmelCase ( self ): '''simple docstring''' return len(self.block_sizes ) @num_blocks.setter def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.' )
316
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ '''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 a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
340
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( 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 A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowercase__ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class SCREAMING_SNAKE_CASE (UpperCAmelCase__ ): lowerCAmelCase = ["pixel_values"] def __init__( self , _UpperCAmelCase = True , _UpperCAmelCase = None , _UpperCAmelCase = PILImageResampling.BICUBIC , _UpperCAmelCase = True , _UpperCAmelCase = None , _UpperCAmelCase = True , _UpperCAmelCase = 1 / 255 , _UpperCAmelCase = True , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = True , **_UpperCAmelCase , ): '''simple docstring''' super().__init__(**_UpperCAmelCase) __A : Union[str, Any] = size if size is not None else {"""shortest_edge""": 224} __A : Dict = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase) __A : int = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __A : Any = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase , param_name='crop_size') __A : Any = do_resize __A : Union[str, Any] = size __A : Union[str, Any] = resample __A : Any = do_center_crop __A : Dict = crop_size __A : List[Any] = do_rescale __A : Union[str, Any] = rescale_factor __A : Optional[int] = do_normalize __A : Tuple = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __A : Any = image_std if image_std is not None else OPENAI_CLIP_STD __A : Dict = do_convert_rgb def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = PILImageResampling.BICUBIC , _UpperCAmelCase = None , **_UpperCAmelCase , ): '''simple docstring''' __A : List[Any] = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}') __A : Optional[int] = get_resize_output_image_size(_UpperCAmelCase , size=size['shortest_edge'] , default_to_square=_UpperCAmelCase) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , **_UpperCAmelCase , ): '''simple docstring''' __A : int = get_size_dict(_UpperCAmelCase) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys (height, width). Got {size.keys()}') return center_crop(_UpperCAmelCase , size=(size['height'], size['width']) , data_format=_UpperCAmelCase , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , **_UpperCAmelCase , ): '''simple docstring''' return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , **_UpperCAmelCase , ): '''simple docstring''' return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = ChannelDimension.FIRST , **_UpperCAmelCase , ): '''simple docstring''' __A : Optional[int] = do_resize if do_resize is not None else self.do_resize __A : Optional[int] = size if size is not None else self.size __A : List[Any] = get_size_dict(_UpperCAmelCase , param_name='size' , default_to_square=_UpperCAmelCase) __A : Any = resample if resample is not None else self.resample __A : Any = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Optional[Any] = crop_size if crop_size is not None else self.crop_size __A : Optional[Any] = get_size_dict(_UpperCAmelCase , param_name='crop_size' , default_to_square=_UpperCAmelCase) __A : Any = do_rescale if do_rescale is not None else self.do_rescale __A : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __A : List[Any] = do_normalize if do_normalize is not None else self.do_normalize __A : Optional[int] = image_mean if image_mean is not None else self.image_mean __A : Tuple = image_std if image_std is not None else self.image_std __A : int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __A : Any = make_list_of_images(_UpperCAmelCase) if not valid_images(_UpperCAmelCase): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None: 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.') # PIL RGBA images are converted to RGB if do_convert_rgb: __A : Tuple = [convert_to_rgb(_UpperCAmelCase) for image in images] # All transformations expect numpy arrays. __A : Any = [to_numpy_array(_UpperCAmelCase) for image in images] if do_resize: __A : Union[str, Any] = [self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase) for image in images] if do_center_crop: __A : Tuple = [self.center_crop(image=_UpperCAmelCase , size=_UpperCAmelCase) for image in images] if do_rescale: __A : List[Any] = [self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase) for image in images] if do_normalize: __A : Union[str, Any] = [self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase) for image in images] __A : List[Any] = [to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase) for image in images] __A : Tuple = {"""pixel_values""": images} return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase)
190
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class __lowercase : """simple docstring""" def __init__( self , A , ) -> List[str]: snake_case : Any = parent snake_case : Optional[int] = 1_3 snake_case : Any = 7 snake_case : List[str] = True snake_case : Union[str, Any] = True snake_case : Any = True snake_case : Any = True snake_case : int = True snake_case : Tuple = False snake_case : List[str] = False snake_case : List[str] = False snake_case : Tuple = 2 snake_case : List[str] = 9_9 snake_case : Dict = 0 snake_case : Dict = 3_2 snake_case : Optional[int] = 2 snake_case : Optional[Any] = 4 snake_case : Any = 0.1 snake_case : str = 0.1 snake_case : Union[str, Any] = 5_1_2 snake_case : List[str] = 1_6 snake_case : str = 2 snake_case : Dict = 0.02 snake_case : Dict = 3 snake_case : str = 4 snake_case : int = """last""" snake_case : List[Any] = True snake_case : Optional[int] = None snake_case : Union[str, Any] = 0 def UpperCAmelCase ( self ) -> Any: snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : Tuple = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) snake_case : Union[str, Any] = None if self.use_input_lengths: snake_case : List[str] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length snake_case : str = None if self.use_token_type_ids: snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) snake_case : int = None snake_case : Optional[Any] = None snake_case : Tuple = None if self.use_labels: snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case : Tuple = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) snake_case : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) snake_case : List[str] = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> Union[str, Any]: snake_case : Optional[Any] = TFFlaubertModel(config=A ) snake_case : List[str] = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} snake_case : List[str] = model(A ) snake_case : List[str] = [input_ids, input_mask] snake_case : int = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> List[Any]: snake_case : int = TFFlaubertWithLMHeadModel(A ) snake_case : Optional[int] = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} snake_case : Dict = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> Any: snake_case : Union[str, Any] = TFFlaubertForQuestionAnsweringSimple(A ) snake_case : Union[str, Any] = {"""input_ids""": input_ids, """lengths""": input_lengths} snake_case : Optional[int] = 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 UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> str: snake_case : int = TFFlaubertForSequenceClassification(A ) snake_case : List[str] = {"""input_ids""": input_ids, """lengths""": input_lengths} snake_case : Any = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> Any: snake_case : Any = self.num_labels snake_case : List[Any] = TFFlaubertForTokenClassification(config=A ) snake_case : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} snake_case : Optional[int] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase ( self , A , A , A , A , A , A , A , A , A , ) -> Dict: snake_case : int = self.num_choices snake_case : Optional[Any] = TFFlaubertForMultipleChoice(config=A ) snake_case : Tuple = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) snake_case : List[str] = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) snake_case : Optional[Any] = tf.tile(tf.expand_dims(A , 1 ) , (1, self.num_choices, 1) ) snake_case : Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } snake_case : Optional[Any] = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase ( self ) -> Dict: snake_case : List[Any] = self.prepare_config_and_inputs() ( snake_case ) : Tuple = config_and_inputs snake_case : Dict = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """langs""": token_type_ids, """lengths""": input_lengths, } return config, inputs_dict @require_tf class __lowercase (UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" _snake_case = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) _snake_case = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _snake_case = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) _snake_case = False _snake_case = False def UpperCAmelCase ( self , A , A , A , A , A ) -> Union[str, Any]: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase ( self ) -> Any: snake_case : Optional[int] = TFFlaubertModelTester(self ) snake_case : List[str] = ConfigTester(self , config_class=A , emb_dim=3_7 ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Optional[Any]: snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*A ) def UpperCAmelCase ( self ) -> List[str]: snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*A ) def UpperCAmelCase ( self ) -> Dict: snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*A ) def UpperCAmelCase ( self ) -> Any: snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*A ) def UpperCAmelCase ( self ) -> Dict: snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*A ) def UpperCAmelCase ( self ) -> Optional[int]: snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*A ) @slow def UpperCAmelCase ( self ) -> str: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Any = TFFlaubertModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_tf @require_sentencepiece @require_tokenizers class __lowercase (unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self ) -> List[Any]: snake_case : List[str] = TFFlaubertModel.from_pretrained("""jplu/tf-flaubert-small-cased""" ) snake_case : List[Any] = tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" snake_case : Optional[Any] = model(A )[0] snake_case : List[str] = tf.TensorShape((1, 8, 5_1_2) ) self.assertEqual(output.shape , A ) # compare the actual values for a slice. snake_case : List[str] = tf.convert_to_tensor( [ [ [-1.8_76_87_73, -1.56_65_55, 0.27_07_24_18], [-1.6_92_00_38, -0.5_87_35_05, 1.9_32_95_99], [-2.9_56_39_85, -1.6_99_38_35, 1.7_97_20_52], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
124
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
0
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy a_ :List[Any] = logging.get_logger(__name__) a_ :Union[str, Any] = { "artists_file": "artists.json", "lyrics_file": "lyrics.json", "genres_file": "genres.json", } a_ :Tuple = { "artists_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json", }, "genres_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json", }, "lyrics_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json", }, } a_ :Optional[int] = { "jukebox": 512, } class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_LYRIC_TOKENS_SIZES _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] def __init__( self : Union[str, Any], _snake_case : Optional[int], _snake_case : int, _snake_case : str, _snake_case : Optional[int]=["v3", "v2", "v2"], _snake_case : List[str]=5_1_2, _snake_case : List[Any]=5, _snake_case : Tuple="<|endoftext|>", **_snake_case : Tuple, ) ->Optional[int]: snake_case__ : str = AddedToken(_snake_case, lstrip=_snake_case, rstrip=_snake_case ) if isinstance(_snake_case, _snake_case ) else unk_token super().__init__( unk_token=_snake_case, n_genres=_snake_case, version=_snake_case, max_n_lyric_tokens=_snake_case, **_snake_case, ) snake_case__ : Optional[Any] = version snake_case__ : int = max_n_lyric_tokens snake_case__ : Optional[Any] = n_genres with open(_snake_case, encoding='utf-8' ) as vocab_handle: snake_case__ : List[str] = json.load(_snake_case ) with open(_snake_case, encoding='utf-8' ) as vocab_handle: snake_case__ : List[str] = json.load(_snake_case ) with open(_snake_case, encoding='utf-8' ) as vocab_handle: snake_case__ : Dict = json.load(_snake_case ) snake_case__ : str = R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 7_9: snake_case__ : int = oov.replace(R'\-\'', R'\-+\'' ) snake_case__ : int = regex.compile(_snake_case ) snake_case__ : Tuple = {v: k for k, v in self.artists_encoder.items()} snake_case__ : List[str] = {v: k for k, v in self.genres_encoder.items()} snake_case__ : Any = {v: k for k, v in self.lyrics_encoder.items()} @property def lowercase_ ( self : str ) ->Optional[int]: return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def lowercase_ ( self : int ) ->List[str]: return dict(self.artists_encoder, self.genres_encoder, self.lyrics_encoder ) def lowercase_ ( self : Dict, _snake_case : Dict, _snake_case : List[Any], _snake_case : Any ) ->List[Any]: snake_case__ : List[str] = [self.artists_encoder.get(_snake_case, 0 ) for artist in list_artists] for genres in range(len(_snake_case ) ): snake_case__ : int = [self.genres_encoder.get(_snake_case, 0 ) for genre in list_genres[genres]] snake_case__ : List[str] = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) snake_case__ : Optional[Any] = [[self.lyrics_encoder.get(_snake_case, 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def lowercase_ ( self : List[Any], _snake_case : Optional[int] ) ->Union[str, Any]: return list(_snake_case ) def lowercase_ ( self : Optional[int], _snake_case : Tuple, _snake_case : Union[str, Any], _snake_case : Union[str, Any], **_snake_case : str ) ->List[Any]: snake_case__ , snake_case__ , snake_case__ : Any = self.prepare_for_tokenization(_snake_case, _snake_case, _snake_case ) snake_case__ : Optional[Any] = self._tokenize(_snake_case ) return artist, genre, lyrics def lowercase_ ( self : Any, _snake_case : str, _snake_case : str, _snake_case : str, _snake_case : bool = False ) ->Tuple[str, str, str, Dict[str, Any]]: for idx in range(len(self.version ) ): if self.version[idx] == "v3": snake_case__ : List[Any] = artists[idx].lower() snake_case__ : Union[str, Any] = [genres[idx].lower()] else: snake_case__ : Optional[int] = self._normalize(artists[idx] ) + '.v2' snake_case__ : Optional[Any] = [ self._normalize(_snake_case ) + '.v2' for genre in genres[idx].split('_' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": snake_case__ : Union[str, Any] = regex.compile(R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+' ) snake_case__ : List[str] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n' snake_case__ : Any = {vocab[index]: index + 1 for index in range(len(_snake_case ) )} snake_case__ : int = 0 snake_case__ : int = len(_snake_case ) + 1 snake_case__ : List[str] = self.vocab snake_case__ : List[str] = {v: k for k, v in self.vocab.items()} snake_case__ : int = '' else: snake_case__ : Any = regex.compile(R'[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+' ) snake_case__ : Any = self._run_strip_accents(_snake_case ) snake_case__ : Optional[Any] = lyrics.replace('\\', '\n' ) snake_case__ : int = self.out_of_vocab.sub('', _snake_case ), [], [] return artists, genres, lyrics def lowercase_ ( self : Tuple, _snake_case : Optional[int] ) ->int: snake_case__ : int = unicodedata.normalize('NFD', _snake_case ) snake_case__ : Union[str, Any] = [] for char in text: snake_case__ : Any = unicodedata.category(_snake_case ) if cat == "Mn": continue output.append(_snake_case ) return "".join(_snake_case ) def lowercase_ ( self : int, _snake_case : str ) ->str: snake_case__ : List[Any] = ( [chr(_snake_case ) for i in range(ord('a' ), ord('z' ) + 1 )] + [chr(_snake_case ) for i in range(ord('A' ), ord('Z' ) + 1 )] + [chr(_snake_case ) for i in range(ord('0' ), ord('9' ) + 1 )] + ['.'] ) snake_case__ : Optional[int] = frozenset(_snake_case ) snake_case__ : Union[str, Any] = re.compile(R'_+' ) snake_case__ : List[Any] = ''.join([c if c in accepted else '_' for c in text.lower()] ) snake_case__ : Tuple = pattern.sub('_', _snake_case ).strip('_' ) return text def lowercase_ ( self : Optional[Any], _snake_case : List[str] ) ->str: return " ".join(_snake_case ) def lowercase_ ( self : Any, _snake_case : Tuple, _snake_case : Optional[Union[str, TensorType]] = None, _snake_case : bool = False ) ->List[str]: # Convert to TensorType if not isinstance(_snake_case, _snake_case ): snake_case__ : Optional[Any] = TensorType(_snake_case ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( 'Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.' ) import tensorflow as tf snake_case__ : str = tf.constant snake_case__ : List[str] = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('Unable to convert output to PyTorch tensors format, PyTorch is not installed.' ) import torch snake_case__ : int = torch.tensor snake_case__ : str = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('Unable to convert output to JAX tensors format, JAX is not installed.' ) import jax.numpy as jnp # noqa: F811 snake_case__ : str = jnp.array snake_case__ : int = _is_jax else: snake_case__ : Any = np.asarray snake_case__ : List[Any] = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: snake_case__ : int = [inputs] if not is_tensor(_snake_case ): snake_case__ : int = as_tensor(_snake_case ) except: # noqa E722 raise ValueError( 'Unable to create tensor, you should probably activate truncation and/or padding ' 'with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.' ) return inputs def __call__( self : List[Any], _snake_case : str, _snake_case : Optional[Any], _snake_case : Union[str, Any]="", _snake_case : List[Any]="pt" ) ->BatchEncoding: snake_case__ : List[str] = [0, 0, 0] snake_case__ : int = [artist] * len(self.version ) snake_case__ : Any = [genres] * len(self.version ) snake_case__ , snake_case__ , snake_case__ : int = self.tokenize(_snake_case, _snake_case, _snake_case ) snake_case__ , snake_case__ , snake_case__ : int = self._convert_token_to_id(_snake_case, _snake_case, _snake_case ) snake_case__ : Optional[int] = [-INFINITY] * len(full_tokens[-1] ) snake_case__ : Tuple = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]], tensor_type=_snake_case ) for i in range(len(self.version ) ) ] return BatchEncoding({'input_ids': input_ids, 'attention_masks': attention_masks} ) def lowercase_ ( self : Dict, _snake_case : str, _snake_case : Optional[str] = None ) ->Tuple[str]: if not os.path.isdir(_snake_case ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return snake_case__ : Dict = os.path.join( _snake_case, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['artists_file'] ) with open(_snake_case, 'w', encoding='utf-8' ) as f: f.write(json.dumps(self.artists_encoder, ensure_ascii=_snake_case ) ) snake_case__ : Optional[int] = os.path.join( _snake_case, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['genres_file'] ) with open(_snake_case, 'w', encoding='utf-8' ) as f: f.write(json.dumps(self.genres_encoder, ensure_ascii=_snake_case ) ) snake_case__ : int = os.path.join( _snake_case, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['lyrics_file'] ) with open(_snake_case, 'w', encoding='utf-8' ) as f: f.write(json.dumps(self.lyrics_encoder, ensure_ascii=_snake_case ) ) return (artists_file, genres_file, lyrics_file) def lowercase_ ( self : Union[str, Any], _snake_case : List[Any], _snake_case : str, _snake_case : List[str] ) ->Optional[int]: snake_case__ : Union[str, Any] = self.artists_decoder.get(_snake_case ) snake_case__ : int = [self.genres_decoder.get(_snake_case ) for genre in genres_index] snake_case__ : int = [self.lyrics_decoder.get(_snake_case ) for character in lyric_index] return artist, genres, lyrics
277
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = TransfoXLTokenizer _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Optional[int] ) ->Any: super().setUp() snake_case__ : Tuple = [ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] snake_case__ : Any = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file, 'w', encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def lowercase_ ( self : Union[str, Any], **_snake_case : List[Any] ) ->Dict: snake_case__ : str = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname, **_snake_case ) def lowercase_ ( self : Optional[Any], _snake_case : str ) ->Dict: snake_case__ : List[Any] = '<unk> UNwanted , running' snake_case__ : List[Any] = '<unk> unwanted, running' return input_text, output_text def lowercase_ ( self : List[Any] ) ->Tuple: snake_case__ : Dict = TransfoXLTokenizer(vocab_file=self.vocab_file, lower_case=_snake_case ) snake_case__ : str = tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(_snake_case, ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ), [0, 4, 8, 7] ) def lowercase_ ( self : List[str] ) ->List[Any]: snake_case__ : str = TransfoXLTokenizer(lower_case=_snake_case ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ), ['hello', '!', 'how', 'are', 'you', '?'] ) def lowercase_ ( self : Optional[int] ) ->Optional[Any]: snake_case__ : Optional[int] = TransfoXLTokenizer(lower_case=_snake_case ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ), ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def lowercase_ ( self : Optional[int] ) ->Union[str, Any]: snake_case__ : List[Any] = TransfoXLTokenizer(lower_case=_snake_case ) snake_case__ : Dict = 'Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' snake_case__ : List[Any] = [ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(_snake_case ), _snake_case ) self.assertEqual(tokenizer.convert_tokens_to_string(_snake_case ), _snake_case ) def lowercase_ ( self : Dict ) ->Any: snake_case__ : Dict = self.get_tokenizer() snake_case__ : Optional[Any] = len(_snake_case ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1', 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(_snake_case ), original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ), [1] ) self.assertEqual(tokenizer.decode([1] ), 'new1' )
277
1
class snake_case__ : """simple docstring""" def __init__( self : Optional[int], _snake_case : int, _snake_case : Union[str, Any]=None, _snake_case : List[Any]=None ) ->Optional[Any]: snake_case__ : Dict = data snake_case__ : int = previous snake_case__ : Tuple = next_node def __str__( self : Optional[Any] ) ->str: return F'''{self.data}''' def lowercase_ ( self : List[Any] ) ->int: return self.data def lowercase_ ( self : Any ) ->Dict: return self.next def lowercase_ ( self : Any ) ->int: return self.previous class snake_case__ : """simple docstring""" def __init__( self : Optional[Any], _snake_case : List[Any] ) ->Any: snake_case__ : int = head def __iter__( self : Dict ) ->int: return self def lowercase_ ( self : List[str] ) ->List[Any]: if not self.current: raise StopIteration else: snake_case__ : Union[str, Any] = self.current.get_data() snake_case__ : Optional[int] = self.current.get_next() return value class snake_case__ : """simple docstring""" def __init__( self : List[Any] ) ->Tuple: snake_case__ : List[str] = None # First node in list snake_case__ : List[str] = None # Last node in list def __str__( self : Optional[Any] ) ->int: snake_case__ : int = self.head snake_case__ : Union[str, Any] = [] while current is not None: nodes.append(current.get_data() ) snake_case__ : Any = current.get_next() return " ".join(str(_snake_case ) for node in nodes ) def __contains__( self : List[Any], _snake_case : int ) ->int: snake_case__ : Union[str, Any] = self.head while current: if current.get_data() == value: return True snake_case__ : Optional[Any] = current.get_next() return False def __iter__( self : str ) ->Dict: return LinkedListIterator(self.head ) def lowercase_ ( self : Dict ) ->List[Any]: if self.head: return self.head.get_data() return None def lowercase_ ( self : List[Any] ) ->Optional[Any]: if self.tail: return self.tail.get_data() return None def lowercase_ ( self : List[Any], _snake_case : Node ) ->None: if self.head is None: snake_case__ : Union[str, Any] = node snake_case__ : Union[str, Any] = node else: self.insert_before_node(self.head, _snake_case ) def lowercase_ ( self : List[Any], _snake_case : Node ) ->None: if self.head is None: self.set_head(_snake_case ) else: self.insert_after_node(self.tail, _snake_case ) def lowercase_ ( self : List[Any], _snake_case : int ) ->None: snake_case__ : Any = Node(_snake_case ) if self.head is None: self.set_head(_snake_case ) else: self.set_tail(_snake_case ) def lowercase_ ( self : List[Any], _snake_case : Node, _snake_case : Node ) ->None: snake_case__ : List[str] = node snake_case__ : str = node.previous if node.get_previous() is None: snake_case__ : int = node_to_insert else: snake_case__ : Union[str, Any] = node_to_insert snake_case__ : int = node_to_insert def lowercase_ ( self : str, _snake_case : Node, _snake_case : Node ) ->None: snake_case__ : Tuple = node snake_case__ : Any = node.next if node.get_next() is None: snake_case__ : Optional[Any] = node_to_insert else: snake_case__ : Optional[int] = node_to_insert snake_case__ : List[Any] = node_to_insert def lowercase_ ( self : Dict, _snake_case : int, _snake_case : int ) ->None: snake_case__ : Optional[int] = 1 snake_case__ : List[Any] = Node(_snake_case ) snake_case__ : Tuple = self.head while node: if current_position == position: self.insert_before_node(_snake_case, _snake_case ) return current_position += 1 snake_case__ : Union[str, Any] = node.next self.insert_after_node(self.tail, _snake_case ) def lowercase_ ( self : str, _snake_case : int ) ->Node: snake_case__ : Optional[Any] = self.head while node: if node.get_data() == item: return node snake_case__ : Optional[Any] = node.get_next() raise Exception('Node not found' ) def lowercase_ ( self : Optional[Any], _snake_case : Tuple ) ->Optional[int]: if (node := self.get_node(_snake_case )) is not None: if node == self.head: snake_case__ : Tuple = self.head.get_next() if node == self.tail: snake_case__ : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(_snake_case ) @staticmethod def lowercase_ ( _snake_case : Node ) ->None: if node.get_next(): snake_case__ : Dict = node.previous if node.get_previous(): snake_case__ : Optional[int] = node.next snake_case__ : Tuple = None snake_case__ : List[Any] = None def lowercase_ ( self : List[str] ) ->str: return self.head is None def lowercase_ (): pass if __name__ == "__main__": import doctest doctest.testmod()
277
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ :Optional[int] = logging.get_logger(__name__) a_ :Dict = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """openai-gpt""" _SCREAMING_SNAKE_CASE = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int], _snake_case : Dict=4_0_4_7_8, _snake_case : str=5_1_2, _snake_case : int=7_6_8, _snake_case : Tuple=1_2, _snake_case : Any=1_2, _snake_case : str="gelu", _snake_case : List[str]=0.1, _snake_case : Any=0.1, _snake_case : Dict=0.1, _snake_case : int=1e-5, _snake_case : Optional[Any]=0.0_2, _snake_case : List[Any]="cls_index", _snake_case : Any=True, _snake_case : Any=None, _snake_case : int=True, _snake_case : Optional[Any]=0.1, **_snake_case : List[Any], ) ->Optional[int]: snake_case__ : int = vocab_size snake_case__ : Dict = n_positions snake_case__ : str = n_embd snake_case__ : str = n_layer snake_case__ : List[Any] = n_head snake_case__ : List[Any] = afn snake_case__ : Optional[Any] = resid_pdrop snake_case__ : List[str] = embd_pdrop snake_case__ : List[Any] = attn_pdrop snake_case__ : Optional[int] = layer_norm_epsilon snake_case__ : str = initializer_range snake_case__ : List[str] = summary_type snake_case__ : Optional[int] = summary_use_proj snake_case__ : List[str] = summary_activation snake_case__ : Optional[Any] = summary_first_dropout snake_case__ : int = summary_proj_to_labels super().__init__(**_snake_case )
277
1
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed 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 ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class snake_case__ : """simple docstring""" def __init__( self : int, _snake_case : str, _snake_case : List[str]=1_3, _snake_case : Union[str, Any]=7, _snake_case : Tuple=True, _snake_case : str=True, _snake_case : List[Any]=True, _snake_case : List[Any]=True, _snake_case : List[Any]=9_9, _snake_case : Any=6_4, _snake_case : Optional[Any]=5, _snake_case : Any=4, _snake_case : Optional[int]=3_7, _snake_case : Tuple="gelu", _snake_case : Any=0.1, _snake_case : Optional[Any]=0.1, _snake_case : Any=5_1_2, _snake_case : Optional[Any]=1_6, _snake_case : List[str]=2, _snake_case : Dict=0.0_2, _snake_case : Dict=3, _snake_case : int=4, _snake_case : Optional[int]=None, ) ->Any: snake_case__ : List[Any] = parent snake_case__ : Tuple = batch_size snake_case__ : Optional[int] = seq_length snake_case__ : List[str] = is_training snake_case__ : Union[str, Any] = use_input_mask snake_case__ : Tuple = use_token_type_ids snake_case__ : Union[str, Any] = use_labels snake_case__ : Union[str, Any] = vocab_size snake_case__ : List[str] = hidden_size snake_case__ : Optional[Any] = num_hidden_layers snake_case__ : Tuple = num_attention_heads snake_case__ : Optional[Any] = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : Tuple = hidden_dropout_prob snake_case__ : Tuple = attention_probs_dropout_prob snake_case__ : Union[str, Any] = max_position_embeddings snake_case__ : int = type_vocab_size snake_case__ : List[Any] = type_sequence_label_size snake_case__ : Any = initializer_range snake_case__ : str = num_labels snake_case__ : str = num_choices snake_case__ : List[Any] = scope snake_case__ : Any = vocab_size - 1 def lowercase_ ( self : int ) ->int: snake_case__ : List[str] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) snake_case__ : int = None if self.use_input_mask: snake_case__ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case__ : str = None if self.use_labels: snake_case__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) snake_case__ : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def lowercase_ ( self : Optional[int] ) ->Optional[Any]: return GPTNeoXConfig( 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=_snake_case, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, ) def lowercase_ ( self : Optional[Any] ) ->Optional[Any]: snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = self.prepare_config_and_inputs() snake_case__ : List[Any] = True return config, input_ids, input_mask, token_labels def lowercase_ ( self : Any, _snake_case : List[str], _snake_case : Optional[Any], _snake_case : Optional[Any] ) ->List[str]: snake_case__ : Any = GPTNeoXModel(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = model(_snake_case, attention_mask=_snake_case ) snake_case__ : List[str] = model(_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : Union[str, Any], _snake_case : Optional[Any], _snake_case : Tuple, _snake_case : List[str] ) ->Optional[Any]: snake_case__ : Any = True snake_case__ : Union[str, Any] = GPTNeoXModel(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Any = model(_snake_case, attention_mask=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : int, _snake_case : int, _snake_case : List[Any], _snake_case : List[str], _snake_case : List[str] ) ->Tuple: snake_case__ : Dict = GPTNeoXForCausalLM(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : List[str] = model(_snake_case, attention_mask=_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ ( self : Optional[int], _snake_case : List[str], _snake_case : Union[str, Any], _snake_case : Optional[Any], _snake_case : Any ) ->List[str]: snake_case__ : Optional[int] = self.num_labels snake_case__ : int = GPTNeoXForQuestionAnswering(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : int = model(_snake_case, attention_mask=_snake_case ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def lowercase_ ( self : Any, _snake_case : Any, _snake_case : Dict, _snake_case : Optional[Any], _snake_case : str ) ->Union[str, Any]: snake_case__ : str = self.num_labels snake_case__ : List[Any] = GPTNeoXForSequenceClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = ids_tensor([self.batch_size], self.type_sequence_label_size ) snake_case__ : Any = model(_snake_case, attention_mask=_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def lowercase_ ( self : Dict, _snake_case : str, _snake_case : Optional[Any], _snake_case : Optional[int], _snake_case : List[Any] ) ->str: snake_case__ : Optional[int] = self.num_labels snake_case__ : List[str] = GPTNeoXForTokenClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = model(_snake_case, attention_mask=_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ ( self : Any, _snake_case : List[str], _snake_case : str, _snake_case : int ) ->str: snake_case__ : Union[str, Any] = True snake_case__ : Union[str, Any] = GPTNeoXForCausalLM(config=_snake_case ) model.to(_snake_case ) model.eval() # first forward pass snake_case__ : Tuple = model(_snake_case, attention_mask=_snake_case, use_cache=_snake_case ) snake_case__ : Optional[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case__ : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) snake_case__ : int = ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and snake_case__ : Any = torch.cat([input_ids, next_tokens], dim=-1 ) snake_case__ : Union[str, Any] = torch.cat([input_mask, next_mask], dim=-1 ) snake_case__ : str = model(_snake_case, attention_mask=_snake_case, output_hidden_states=_snake_case ) snake_case__ : int = output_from_no_past['hidden_states'][0] snake_case__ : Optional[Any] = model( _snake_case, attention_mask=_snake_case, past_key_values=_snake_case, output_hidden_states=_snake_case, )['hidden_states'][0] # select random slice snake_case__ : int = ids_tensor((1,), output_from_past.shape[-1] ).item() snake_case__ : int = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case__ : Dict = 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(_snake_case, _snake_case, atol=1e-3 ) ) def lowercase_ ( self : str ) ->Union[str, Any]: snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = config_and_inputs snake_case__ : Tuple = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = (GPTNeoXForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = ( { """feature-extraction""": GPTNeoXModel, """question-answering""": GPTNeoXForQuestionAnswering, """text-classification""": GPTNeoXForSequenceClassification, """text-generation""": GPTNeoXForCausalLM, """token-classification""": GPTNeoXForTokenClassification, """zero-shot""": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Optional[int] ) ->List[Any]: snake_case__ : Optional[int] = GPTNeoXModelTester(self ) snake_case__ : Optional[Any] = ConfigTester(self, config_class=_snake_case, hidden_size=6_4, num_attention_heads=8 ) def lowercase_ ( self : List[str] ) ->Any: self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ) ->List[str]: snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(_snake_case, _snake_case, _snake_case ) def lowercase_ ( self : Tuple ) ->int: snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(_snake_case, _snake_case, _snake_case ) def lowercase_ ( self : Optional[Any] ) ->str: # This regression test was failing with PyTorch < 1.3 snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(_snake_case, _snake_case, _snake_case ) def lowercase_ ( self : Union[str, Any] ) ->Tuple: snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(_snake_case, _snake_case, _snake_case ) def lowercase_ ( self : Any ) ->List[Any]: snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*_snake_case ) def lowercase_ ( self : Tuple ) ->List[str]: snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_snake_case ) def lowercase_ ( self : Tuple ) ->Dict: snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_snake_case ) def lowercase_ ( self : List[str] ) ->int: snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) @unittest.skip(reason='Feed forward chunking is not implemented' ) def lowercase_ ( self : Any ) ->List[str]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def lowercase_ ( self : List[str], _snake_case : Tuple ) ->List[Any]: snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = ids_tensor([1, 1_0], config.vocab_size ) snake_case__ : List[Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )], config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights snake_case__ : Dict = GPTNeoXModel(_snake_case ) original_model.to(_snake_case ) original_model.eval() snake_case__ : List[str] = original_model(_snake_case ).last_hidden_state snake_case__ : int = original_model(_snake_case ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights snake_case__ : str = {'type': scaling_type, 'factor': 1_0.0} snake_case__ : str = GPTNeoXModel(_snake_case ) scaled_model.to(_snake_case ) scaled_model.eval() snake_case__ : str = scaled_model(_snake_case ).last_hidden_state snake_case__ : Union[str, Any] = scaled_model(_snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_snake_case, _snake_case, atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_snake_case, _snake_case, atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_snake_case, _snake_case, atol=1e-5 ) ) @require_torch class snake_case__ ( unittest.TestCase ): """simple docstring""" @slow def lowercase_ ( self : List[Any] ) ->Union[str, Any]: snake_case__ : int = AutoTokenizer.from_pretrained('EleutherAI/pythia-410m-deduped' ) for checkpointing in [True, False]: snake_case__ : Any = GPTNeoXForCausalLM.from_pretrained('EleutherAI/pythia-410m-deduped' ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(_snake_case ) snake_case__ : int = tokenizer('My favorite food is', return_tensors='pt' ).to(_snake_case ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 snake_case__ : Union[str, Any] = 'My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI\'m not sure' snake_case__ : List[Any] = model.generate(**_snake_case, do_sample=_snake_case, max_new_tokens=2_0 ) snake_case__ : str = tokenizer.batch_decode(_snake_case )[0] self.assertEqual(_snake_case, _snake_case )
277
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel a_ :Optional[Any] = logging.getLogger(__name__) def lowercase_ (A : List[Any] , A : List[Any] ): # save results if os.path.exists(A ): if os.path.exists(os.path.join(A , 'config.json' ) ) and os.path.isfile( os.path.join(A , 'config.json' ) ): os.remove(os.path.join(A , 'config.json' ) ) if os.path.exists(os.path.join(A , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(A , 'pytorch_model.bin' ) ): os.remove(os.path.join(A , 'pytorch_model.bin' ) ) else: os.makedirs(A ) model.save_pretrained(A ) def lowercase_ (A : Any , A : Optional[Any]=False ): snake_case__ : str = 2 if unlogit: snake_case__ : Dict = torch.pow(A , A ) snake_case__ : Any = p * torch.log(A ) snake_case__ : Tuple = 0 return -plogp.sum(dim=-1 ) def lowercase_ (A : List[str] ): logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(A ) ) ) ) for row in range(len(A ) ): if tensor.dtype != torch.long: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:d}''' for x in tensor[row].cpu().data ) ) def lowercase_ (A : Tuple , A : Optional[Any] , A : str , A : int=True , A : Optional[int]=True , A : Any=None , A : int=False ): snake_case__ , snake_case__ : Optional[Any] = model.config.num_hidden_layers, model.config.num_attention_heads snake_case__ : int = torch.zeros(A , A ).to(args.device ) snake_case__ : Any = torch.zeros(A , A ).to(args.device ) if head_mask is None: snake_case__ : Dict = torch.ones(A , A ).to(args.device ) head_mask.requires_grad_(requires_grad=A ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: snake_case__ : Optional[int] = None snake_case__ : List[Any] = 0.0 snake_case__ : str = 0.0 for step, inputs in enumerate(tqdm(A , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): snake_case__ : Union[str, Any] = tuple(t.to(args.device ) for t in inputs ) ((snake_case__) , ) : Optional[Any] = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) snake_case__ : Union[str, Any] = model(A , labels=A , head_mask=A ) # (loss), lm_logits, presents, (all hidden_states), (attentions) snake_case__ , snake_case__ , snake_case__ : Dict = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(A ): snake_case__ : Optional[Any] = entropy(attn.detach() , A ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(A ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: snake_case__ : Union[str, Any] = 2 snake_case__ : List[Any] = torch.pow(torch.pow(A , A ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: snake_case__ : Tuple = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(A ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(A ) logger.info('Head ranked by importance scores' ) snake_case__ : Tuple = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) snake_case__ : Union[str, Any] = torch.arange( head_importance.numel() , device=args.device ) snake_case__ : str = head_ranks.view_as(A ) print_ad_tensor(A ) return attn_entropy, head_importance, total_loss def lowercase_ (A : Optional[int] , A : Dict , A : Optional[int] ): snake_case__ , snake_case__ , snake_case__ : Any = compute_heads_importance(A , A , A , compute_entropy=A ) snake_case__ : Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , A , original_score * args.masking_threshold ) snake_case__ : Optional[Any] = torch.ones_like(A ) snake_case__ : Union[str, Any] = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) snake_case__ : Dict = original_score while current_score >= original_score * args.masking_threshold: snake_case__ : int = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads snake_case__ : List[Any] = float('Inf' ) snake_case__ : Union[str, Any] = head_importance.view(-1 ).sort()[1] if len(A ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads snake_case__ : int = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) snake_case__ : int = new_head_mask.view(-1 ) snake_case__ : int = 0.0 snake_case__ : Union[str, Any] = new_head_mask.view_as(A ) snake_case__ : List[str] = new_head_mask.clone().detach() print_ad_tensor(A ) # Compute metric and head importance again snake_case__ , snake_case__ , snake_case__ : Any = compute_heads_importance( A , A , A , compute_entropy=A , head_mask=A ) snake_case__ : Dict = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , A , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(A ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def lowercase_ (A : List[str] , A : Tuple , A : Optional[Any] , A : int ): snake_case__ : Any = datetime.now() snake_case__ , snake_case__ , snake_case__ : str = compute_heads_importance( A , A , A , compute_entropy=A , compute_importance=A , head_mask=A ) snake_case__ : Tuple = 1 / loss snake_case__ : Dict = datetime.now() - before_time snake_case__ : Union[str, Any] = sum(p.numel() for p in model.parameters() ) snake_case__ : Optional[Any] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(A ) ) } for k, v in heads_to_prune.items(): if isinstance(A , A ): snake_case__ : Any = [ v, ] assert sum(len(A ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(A ) snake_case__ : Dict = sum(p.numel() for p in model.parameters() ) snake_case__ : Tuple = datetime.now() snake_case__ , snake_case__ , snake_case__ : Dict = compute_heads_importance( A , A , A , compute_entropy=A , compute_importance=A , head_mask=A , actually_pruned=A , ) snake_case__ : Any = 1 / loss snake_case__ : int = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , A , A , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , A , A ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(A , args.output_dir ) def lowercase_ (): snake_case__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=A , type=A , required=A , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) 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( '--output_dir' , default=A , type=A , required=A , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=A , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=A , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=A , type=A , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=A , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=A , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=A , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=A , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=A , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=A , help='Batch size.' ) parser.add_argument('--seed' , type=A , default=4_2 ) parser.add_argument('--local_rank' , type=A , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=A , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=A , default='' , help='Can be used for distant debugging.' ) snake_case__ : Optional[int] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=A ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: snake_case__ : List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) snake_case__ : Optional[Any] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) snake_case__ : int = torch.device('cuda' , args.local_rank ) snake_case__ : List[str] = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) snake_case__ : Any = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: snake_case__ : List[str] = nn.parallel.DistributedDataParallel( A , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=A ) elif args.n_gpu > 1: snake_case__ : Optional[int] = nn.DataParallel(A ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=A ) torch.save(A , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , A ) # Prepare dataset snake_case__ : Optional[Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) snake_case__ : List[str] = (torch.from_numpy(A ),) snake_case__ : int = TensorDataset(*A ) snake_case__ : Union[str, Any] = RandomSampler(A ) snake_case__ : Any = DataLoader(A , sampler=A , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(A , A , A ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: snake_case__ : Dict = mask_heads(A , A , A ) prune_heads(A , A , A , A ) if __name__ == "__main__": main()
277
1
from math import factorial, radians def lowercase_ (A : float , A : int = 1_8 , A : int = 1_0 ): snake_case__ : List[str] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians snake_case__ : Union[str, Any] = radians(A ) snake_case__ : int = angle_in_radians snake_case__ : List[str] = 3 snake_case__ : int = -1 for _ in range(A ): result += (b * (angle_in_radians**a)) / factorial(A ) snake_case__ : int = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(A , A ) if __name__ == "__main__": __import__("doctest").testmod()
277
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() a_ :Dict = logging.get_logger(__name__) def lowercase_ (A : Optional[Any] , A : Any=False ): snake_case__ : List[Any] = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('head' ): snake_case__ : str = 'segformer.encoder.' + key if key.startswith('backbone' ): snake_case__ : str = key.replace('backbone' , 'segformer.encoder' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 snake_case__ : Optional[int] = key[key.find('patch_embed' ) + len('patch_embed' )] snake_case__ : int = key.replace(F'''patch_embed{idx}''' , F'''patch_embeddings.{int(A )-1}''' ) if "norm" in key: snake_case__ : Optional[int] = key.replace('norm' , 'layer_norm' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 snake_case__ : Tuple = key[key.find('segformer.encoder.layer_norm' ) + len('segformer.encoder.layer_norm' )] snake_case__ : Union[str, Any] = key.replace(F'''layer_norm{idx}''' , F'''layer_norm.{int(A )-1}''' ) if "layer_norm1" in key: snake_case__ : List[Any] = key.replace('layer_norm1' , 'layer_norm_1' ) if "layer_norm2" in key: snake_case__ : List[Any] = key.replace('layer_norm2' , 'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 snake_case__ : List[Any] = key[key.find('block' ) + len('block' )] snake_case__ : List[Any] = key.replace(F'''block{idx}''' , F'''block.{int(A )-1}''' ) if "attn.q" in key: snake_case__ : int = key.replace('attn.q' , 'attention.self.query' ) if "attn.proj" in key: snake_case__ : str = key.replace('attn.proj' , 'attention.output.dense' ) if "attn" in key: snake_case__ : Optional[int] = key.replace('attn' , 'attention.self' ) if "fc1" in key: snake_case__ : str = key.replace('fc1' , 'dense1' ) if "fc2" in key: snake_case__ : Dict = key.replace('fc2' , 'dense2' ) if "linear_pred" in key: snake_case__ : Union[str, Any] = key.replace('linear_pred' , 'classifier' ) if "linear_fuse" in key: snake_case__ : List[str] = key.replace('linear_fuse.conv' , 'linear_fuse' ) snake_case__ : List[Any] = key.replace('linear_fuse.bn' , 'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 snake_case__ : Optional[int] = key[key.find('linear_c' ) + len('linear_c' )] snake_case__ : Tuple = key.replace(F'''linear_c{idx}''' , F'''linear_c.{int(A )-1}''' ) if key.startswith('head' ): snake_case__ : Tuple = key.replace('head' , 'classifier' ) snake_case__ : Optional[int] = value return new_state_dict def lowercase_ (A : Tuple , A : Optional[int] ): # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) snake_case__ : List[str] = state_dict.pop(F'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''' ) snake_case__ : Optional[Any] = state_dict.pop(F'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict snake_case__ : str = kv_weight[ : config.hidden_sizes[i], : ] snake_case__ : Dict = kv_bias[: config.hidden_sizes[i]] snake_case__ : List[str] = kv_weight[ config.hidden_sizes[i] :, : ] snake_case__ : List[Any] = kv_bias[ config.hidden_sizes[i] : ] def lowercase_ (): snake_case__ : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : Dict = Image.open(requests.get(A , stream=A ).raw ) return image @torch.no_grad() def lowercase_ (A : Any , A : Union[str, Any] , A : Optional[Any] ): snake_case__ : List[str] = SegformerConfig() snake_case__ : Dict = False # set attributes based on model_name snake_case__ : Optional[int] = 'huggingface/label-files' if "segformer" in model_name: snake_case__ : str = model_name[len('segformer.' ) : len('segformer.' ) + 2] if "ade" in model_name: snake_case__ : Optional[int] = 1_5_0 snake_case__ : int = 'ade20k-id2label.json' snake_case__ : List[Any] = (1, 1_5_0, 1_2_8, 1_2_8) elif "city" in model_name: snake_case__ : str = 1_9 snake_case__ : List[str] = 'cityscapes-id2label.json' snake_case__ : Optional[Any] = (1, 1_9, 1_2_8, 1_2_8) else: raise ValueError(F'''Model {model_name} not supported''' ) elif "mit" in model_name: snake_case__ : str = True snake_case__ : Union[str, Any] = model_name[4:6] snake_case__ : Optional[Any] = 1_0_0_0 snake_case__ : Optional[int] = 'imagenet-1k-id2label.json' snake_case__ : List[Any] = (1, 1_0_0_0) else: raise ValueError(F'''Model {model_name} not supported''' ) # set config attributes snake_case__ : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) snake_case__ : List[Any] = {int(A ): v for k, v in idalabel.items()} snake_case__ : Union[str, Any] = idalabel snake_case__ : Tuple = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": snake_case__ : List[Any] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Tuple = 2_5_6 elif size == "b2": snake_case__ : List[str] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : int = 7_6_8 snake_case__ : List[Any] = [3, 4, 6, 3] elif size == "b3": snake_case__ : Optional[Any] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : int = 7_6_8 snake_case__ : Optional[Any] = [3, 4, 1_8, 3] elif size == "b4": snake_case__ : str = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Optional[Any] = 7_6_8 snake_case__ : Union[str, Any] = [3, 8, 2_7, 3] elif size == "b5": snake_case__ : List[str] = [6_4, 1_2_8, 3_2_0, 5_1_2] snake_case__ : Optional[Any] = 7_6_8 snake_case__ : Any = [3, 6, 4_0, 3] else: raise ValueError(F'''Size {size} not supported''' ) # load image processor (only resize + normalize) snake_case__ : Dict = SegformerImageProcessor( image_scale=(5_1_2, 5_1_2) , keep_ratio=A , align=A , do_random_crop=A ) # prepare image snake_case__ : List[str] = prepare_img() snake_case__ : Dict = image_processor(images=A , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict if encoder_only: snake_case__ : Tuple = torch.load(A , map_location=torch.device('cpu' ) ) else: snake_case__ : int = torch.load(A , map_location=torch.device('cpu' ) )['state_dict'] # rename keys snake_case__ : List[Any] = rename_keys(A , encoder_only=A ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(A , A ) # create HuggingFace model and load state dict if encoder_only: snake_case__ : str = False snake_case__ : List[Any] = SegformerForImageClassification(A ) else: snake_case__ : Dict = SegformerForSemanticSegmentation(A ) model.load_state_dict(A ) model.eval() # forward pass snake_case__ : int = model(A ) snake_case__ : Any = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": snake_case__ : Dict = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": snake_case__ : Optional[int] = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": snake_case__ : List[Any] = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": snake_case__ : Union[str, Any] = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": snake_case__ : Dict = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": snake_case__ : List[Any] = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": snake_case__ : str = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": snake_case__ : Tuple = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": snake_case__ : Any = torch.tensor( [ [ [-1.1_372e01, -1.2_787e01, -1.3_477e01], [-1.2_536e01, -1.4_194e01, -1.4_409e01], [-1.3_217e01, -1.4_888e01, -1.5_327e01], ], [ [-1.4_791e01, -1.7_122e01, -1.8_277e01], [-1.7_163e01, -1.9_192e01, -1.9_533e01], [-1.7_897e01, -1.9_991e01, -2.0_315e01], ], [ [7.6_723e-01, 4.1_921e-01, -7.7_878e-02], [4.7_772e-01, 9.5_557e-03, -2.8_082e-01], [3.6_032e-01, -2.4_826e-01, -5.1_168e-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": snake_case__ : Optional[int] = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": snake_case__ : Union[str, Any] = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": snake_case__ : List[str] = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": snake_case__ : List[Any] = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": snake_case__ : str = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": snake_case__ : List[str] = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: snake_case__ : Tuple = logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , A , atol=1e-2 ) # finally, save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) if __name__ == "__main__": a_ :Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model_name", default="segformer.b0.512x512.ade.160k", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) a_ :Union[str, Any] = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
277
1
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a_ :str = logging.get_logger(__name__) def lowercase_ (A : str ): snake_case__ : Tuple = SwinConfig.from_pretrained( 'microsoft/swin-tiny-patch4-window7-224' , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) snake_case__ : List[Any] = MaskFormerConfig(backbone_config=A ) snake_case__ : Union[str, Any] = 'huggingface/label-files' if "ade20k-full" in model_name: # this should be ok snake_case__ : Dict = 8_4_7 snake_case__ : List[str] = 'maskformer-ade20k-full-id2label.json' elif "ade" in model_name: # this should be ok snake_case__ : Union[str, Any] = 1_5_0 snake_case__ : Any = 'ade20k-id2label.json' elif "coco-stuff" in model_name: # this should be ok snake_case__ : List[str] = 1_7_1 snake_case__ : Union[str, Any] = 'maskformer-coco-stuff-id2label.json' elif "coco" in model_name: # TODO snake_case__ : Dict = 1_3_3 snake_case__ : str = 'coco-panoptic-id2label.json' elif "cityscapes" in model_name: # this should be ok snake_case__ : List[str] = 1_9 snake_case__ : Union[str, Any] = 'cityscapes-id2label.json' elif "vistas" in model_name: # this should be ok snake_case__ : Tuple = 6_5 snake_case__ : List[str] = 'mapillary-vistas-id2label.json' snake_case__ : Dict = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) snake_case__ : List[str] = {int(A ): v for k, v in idalabel.items()} return config def lowercase_ (A : Any ): snake_case__ : Optional[int] = [] # stem # fmt: off rename_keys.append(('backbone.patch_embed.proj.weight', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.proj.bias', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'model.pixel_level_module.encoder.model.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'model.pixel_level_module.encoder.model.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.layers.{i}.downsample.reduction.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(('sem_seg_head.layer_4.weight', 'model.pixel_level_module.decoder.fpn.stem.0.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.weight', 'model.pixel_level_module.decoder.fpn.stem.1.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.bias', 'model.pixel_level_module.decoder.fpn.stem.1.bias') ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((F'''sem_seg_head.adapter_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(('sem_seg_head.mask_features.weight', 'model.pixel_level_module.decoder.mask_projection.weight') ) rename_keys.append(('sem_seg_head.mask_features.bias', 'model.pixel_level_module.decoder.mask_projection.bias') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.weight', 'model.transformer_module.decoder.layernorm.weight') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.bias', 'model.transformer_module.decoder.layernorm.bias') ) # heads on top rename_keys.append(('sem_seg_head.predictor.query_embed.weight', 'model.transformer_module.queries_embedder.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.weight', 'model.transformer_module.input_projection.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.bias', 'model.transformer_module.input_projection.bias') ) rename_keys.append(('sem_seg_head.predictor.class_embed.weight', 'class_predictor.weight') ) rename_keys.append(('sem_seg_head.predictor.class_embed.bias', 'class_predictor.bias') ) for i in range(3 ): rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', F'''mask_embedder.{i}.0.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', F'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def lowercase_ (A : Tuple , A : Tuple , A : Optional[Any] ): snake_case__ : Optional[int] = dct.pop(A ) snake_case__ : Union[str, Any] = val def lowercase_ (A : Optional[Any] , A : Tuple ): snake_case__ : Optional[int] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): snake_case__ : Optional[int] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) snake_case__ : int = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) snake_case__ : Tuple = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : str = in_proj_weight[:dim, :] snake_case__ : int = in_proj_bias[: dim] snake_case__ : List[Any] = in_proj_weight[ dim : dim * 2, : ] snake_case__ : List[str] = in_proj_bias[ dim : dim * 2 ] snake_case__ : List[Any] = in_proj_weight[ -dim :, : ] snake_case__ : Dict = in_proj_bias[-dim :] # fmt: on def lowercase_ (A : List[str] , A : List[Any] ): # fmt: off snake_case__ : str = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) snake_case__ : int = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Any = in_proj_weight[: hidden_size, :] snake_case__ : Tuple = in_proj_bias[:config.hidden_size] snake_case__ : List[str] = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : Dict = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : Any = in_proj_weight[-hidden_size :, :] snake_case__ : int = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) snake_case__ : List[str] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[: hidden_size, :] snake_case__ : Optional[Any] = in_proj_bias[:config.hidden_size] snake_case__ : int = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : List[str] = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : List[str] = in_proj_weight[-hidden_size :, :] snake_case__ : str = in_proj_bias[-hidden_size :] # fmt: on def lowercase_ (): snake_case__ : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : int = Image.open(requests.get(A , stream=A ).raw ) return im @torch.no_grad() def lowercase_ (A : str , A : str , A : str , A : bool = False ): snake_case__ : Optional[int] = get_maskformer_config(A ) # load original state_dict with open(A , 'rb' ) as f: snake_case__ : List[Any] = pickle.load(A ) snake_case__ : Optional[int] = data['model'] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys snake_case__ : List[str] = create_rename_keys(A ) for src, dest in rename_keys: rename_key(A , A , A ) read_in_swin_q_k_v(A , config.backbone_config ) read_in_decoder_q_k_v(A , A ) # update to torch tensors for key, value in state_dict.items(): snake_case__ : int = torch.from_numpy(A ) # load 🤗 model snake_case__ : str = MaskFormerForInstanceSegmentation(A ) model.eval() for name, param in model.named_parameters(): print(A , param.shape ) snake_case__ , snake_case__ : Union[str, Any] = model.load_state_dict(A , strict=A ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(A ) == 0, F'''Unexpected keys: {unexpected_keys}''' # verify results snake_case__ : Optional[Any] = prepare_img() if "vistas" in model_name: snake_case__ : int = 6_5 elif "cityscapes" in model_name: snake_case__ : Dict = 6_5_5_3_5 else: snake_case__ : Tuple = 2_5_5 snake_case__ : Optional[int] = True if 'ade' in model_name else False snake_case__ : Dict = MaskFormerImageProcessor(ignore_index=A , reduce_labels=A ) snake_case__ : Any = image_processor(A , return_tensors='pt' ) snake_case__ : Any = model(**A ) print('Logits:' , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": snake_case__ : Tuple = torch.tensor( [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , A , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) if push_to_hub: print('Pushing model and image processor to the hub...' ) model.push_to_hub(F'''nielsr/{model_name}''' ) image_processor.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a_ :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="maskformer-swin-tiny-ade", type=str, help=("Name of the MaskFormer model you'd like to convert",), ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl", type=str, help="Path to the original state dict (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a_ :Dict = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
277
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a_ :List[Any] = logging.get_logger(__name__) a_ :List[Any] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } a_ :List[Any] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def lowercase_ (A : Dict ): snake_case__ : Optional[Any] = {} with open(A , 'r' ) as file: for line_number, line in enumerate(A ): snake_case__ : Dict = line.strip() if line: snake_case__ : int = line.split() snake_case__ : List[str] = line_number snake_case__ : Dict = words[0] snake_case__ : Optional[Any] = value return result def lowercase_ (A : int , A : int , A : Optional[int] , A : Optional[Any] , A : Tuple ): for attribute in key.split('.' ): snake_case__ : Optional[int] = getattr(A , A ) snake_case__ : Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(A ): snake_case__ : List[str] = PARAM_MAPPING[full_name.split('.' )[-1]] snake_case__ : Dict = 'param' if weight_type is not None and weight_type != "param": snake_case__ : Union[str, Any] = getattr(A , A ).shape elif weight_type is not None and weight_type == "param": snake_case__ : Optional[int] = hf_pointer for attribute in hf_param_name.split('.' ): snake_case__ : Optional[Any] = getattr(A , A ) snake_case__ : Dict = shape_pointer.shape # let's reduce dimension snake_case__ : List[Any] = value[0] else: snake_case__ : Union[str, Any] = 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": snake_case__ : Any = value elif weight_type == "weight_g": snake_case__ : List[Any] = value elif weight_type == "weight_v": snake_case__ : Any = value elif weight_type == "bias": snake_case__ : List[Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): snake_case__ : int = getattr(A , A ) snake_case__ : Optional[int] = value else: snake_case__ : Optional[Any] = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowercase_ (A : Tuple , A : List[Any] , A : int , A : str , A : Tuple ): snake_case__ : Optional[int] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(A ): snake_case__ : List[str] = PARAM_MAPPING[full_name.split('.' )[-1]] snake_case__ : str = 'param' if weight_type is not None and weight_type != "param": snake_case__ : int = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case__ : Any = '.'.join([key, hf_param_name] ) else: snake_case__ : Dict = key snake_case__ : List[str] = value if 'lm_head' in full_key else value[0] a_ :List[str] = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def lowercase_ (A : str , A : Optional[Any] , A : Optional[Any]=None , A : List[str]=None ): snake_case__ : Optional[int] = False for key, mapped_key in MAPPING.items(): snake_case__ : Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case__ : Optional[int] = True if "*" in mapped_key: snake_case__ : List[Any] = name.split(A )[0].split('.' )[-2] snake_case__ : Union[str, Any] = mapped_key.replace('*' , A ) if "weight_g" in name: snake_case__ : Tuple = 'weight_g' elif "weight_v" in name: snake_case__ : List[str] = 'weight_v' elif "bias" in name: snake_case__ : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case__ : Optional[int] = 'weight' else: snake_case__ : str = None if hf_dict is not None: rename_dict(A , A , A , A , A ) else: set_recursively(A , A , A , A , A ) return is_used return is_used def lowercase_ (A : Optional[Any] , A : Dict , A : Optional[int] ): snake_case__ : Dict = [] snake_case__ : Tuple = fairseq_model.state_dict() snake_case__ : str = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case__ : str = False if "conv_layers" in name: load_conv_layer( A , A , A , A , hf_model.config.feat_extract_norm == 'group' , ) snake_case__ : Any = True else: snake_case__ : Dict = load_wavaveca_layer(A , A , A ) if not is_used: unused_weights.append(A ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowercase_ (A : Dict , A : Optional[Any] , A : Tuple , A : str , A : List[str] ): snake_case__ : List[Any] = full_name.split('conv_layers.' )[-1] snake_case__ : List[str] = name.split('.' ) snake_case__ : List[Any] = int(items[0] ) snake_case__ : str = 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.''' ) 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.''' ) snake_case__ : str = 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.''' ) snake_case__ : str = 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.''' ) snake_case__ : int = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(A ) @torch.no_grad() def lowercase_ (A : Union[str, Any] , A : str , A : Tuple=None , A : List[str]=None , A : Any=True , A : Optional[int]=False ): if config_path is not None: snake_case__ : List[Any] = WavaVecaConfig.from_pretrained(A ) else: snake_case__ : List[Any] = WavaVecaConfig() if is_seq_class: snake_case__ : Dict = read_txt_into_dict(A ) snake_case__ : Any = idalabel snake_case__ : Union[str, Any] = WavaVecaForSequenceClassification(A ) snake_case__ : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=A , return_attention_mask=A , ) feature_extractor.save_pretrained(A ) elif is_finetuned: if dict_path: snake_case__ : str = Dictionary.load(A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case__ : List[str] = target_dict.pad_index snake_case__ : Optional[int] = target_dict.bos_index snake_case__ : Optional[int] = target_dict.eos_index snake_case__ : List[Any] = len(target_dict.symbols ) snake_case__ : str = os.path.join(A , 'vocab.json' ) if not os.path.isdir(A ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(A ) ) return os.makedirs(A , exist_ok=A ) snake_case__ : Optional[Any] = target_dict.indices # fairseq has the <pad> and <s> switched snake_case__ : Optional[Any] = 0 snake_case__ : Union[str, Any] = 1 with open(A , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(A , A ) snake_case__ : List[Any] = WavaVecaCTCTokenizer( A , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=A , ) snake_case__ : str = True if config.feat_extract_norm == 'layer' else False snake_case__ : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=A , return_attention_mask=A , ) snake_case__ : Union[str, Any] = WavaVecaProcessor(feature_extractor=A , tokenizer=A ) processor.save_pretrained(A ) snake_case__ : str = WavaVecaForCTC(A ) else: snake_case__ : int = WavaVecaForPreTraining(A ) if is_finetuned or is_seq_class: snake_case__ , snake_case__ , snake_case__ : str = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: snake_case__ : Tuple = argparse.Namespace(task='audio_pretraining' ) snake_case__ : str = fairseq.tasks.setup_task(A ) snake_case__ , snake_case__ , snake_case__ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=A ) snake_case__ : List[Any] = model[0].eval() recursively_load_weights(A , A , not is_finetuned ) hf_wavavec.save_pretrained(A ) if __name__ == "__main__": a_ :List[Any] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) a_ :str = parser.parse_args() a_ :Tuple = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
277
1
def lowercase_ (A : list[int] ): snake_case__ : int = len(A ) for i in range(A ): for j in range(i + 1 , A ): if numbers[j] < numbers[i]: snake_case__ , snake_case__ : Dict = numbers[j], numbers[i] return numbers if __name__ == "__main__": a_ :List[Any] = input("Enter numbers separated by a comma:\n").strip() a_ :Union[str, Any] = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
277
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo a_ :Any = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" a_ :List[str] = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" a_ :List[str] = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): """simple docstring""" def lowercase_ ( self : str ) ->MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), id='references' ), } ), ) def lowercase_ ( self : str, _snake_case : List[List[List[str]]], _snake_case : List[List[str]], _snake_case : int = 1, _snake_case : int = 4, ) ->Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_snake_case, hypotheses=_snake_case, min_len=_snake_case, max_len=_snake_case ) }
277
1
def lowercase_ (A : int = 1_0 , A : int = 2_2 ): snake_case__ : Optional[int] = range(1 , A ) snake_case__ : Optional[int] = range(1 , A ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F"""{solution(10, 22) = }""")
277
from math import factorial def lowercase_ (A : int , A : int , A : float ): if successes > trials: raise ValueError('successes must be lower or equal to trials' ) if trials < 0 or successes < 0: raise ValueError('the function is defined for non-negative integers' ) if not isinstance(A , A ) or not isinstance(A , A ): raise ValueError('the function is defined for non-negative integers' ) if not 0 < prob < 1: raise ValueError('prob has to be in range of 1 - 0' ) snake_case__ : List[Any] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! snake_case__ : List[str] = float(factorial(A ) ) coefficient /= factorial(A ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
277
1
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a_ :List[Any] = "." # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) a_ :Optional[int] = [ "Assert", "AssignVariableOp", "EmptyTensorList", "MergeV2Checkpoints", "ReadVariableOp", "ResourceGather", "RestoreV2", "SaveV2", "ShardedFilename", "StatefulPartitionedCall", "StaticRegexFullMatch", "VarHandleOp", ] def lowercase_ (A : Union[str, Any] , A : Union[str, Any] , A : Union[str, Any] ): snake_case__ : Optional[int] = SavedModel() snake_case__ : Any = [] with open(os.path.join(A , 'utils' , 'tf_ops' , 'onnx.json' ) ) as f: snake_case__ : List[str] = json.load(A )['opsets'] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(A )] ) with open(A , 'rb' ) as f: saved_model.ParseFromString(f.read() ) snake_case__ : int = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want snake_case__ : Optional[Any] = sorted(A ) snake_case__ : str = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(A ) if strict and len(A ) > 0: raise Exception(F'''Found the following incompatible ops for the opset {opset}:\n''' + incompatible_ops ) elif len(A ) > 0: print(F'''Found the following incompatible ops for the opset {opset}:''' ) print(*A , sep='\n' ) else: print(F'''The saved model {saved_model_path} can properly be converted with ONNX.''' ) if __name__ == "__main__": a_ :str = argparse.ArgumentParser() parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") parser.add_argument( "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." ) parser.add_argument( "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." ) parser.add_argument( "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" ) a_ :str = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
277
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline a_ :List[Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase_ ) class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any], **_snake_case : str ) ->Dict: super().__init__(**_snake_case ) if self.framework != "pt": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self : Union[str, Any], _snake_case : Union[np.ndarray, bytes, str], **_snake_case : Tuple ) ->Dict: return super().__call__(_snake_case, **_snake_case ) def lowercase_ ( self : Tuple, **_snake_case : Any ) ->Union[str, Any]: snake_case__ : str = {} if "candidate_labels" in kwargs: snake_case__ : str = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: snake_case__ : str = kwargs['hypothesis_template'] return preprocess_params, {}, {} def lowercase_ ( self : Dict, _snake_case : str, _snake_case : Optional[int]=None, _snake_case : List[str]="This is a sound of {}." ) ->int: if isinstance(_snake_case, _snake_case ): if audio.startswith('http://' ) or audio.startswith('https://' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png snake_case__ : List[Any] = requests.get(_snake_case ).content else: with open(_snake_case, 'rb' ) as f: snake_case__ : Union[str, Any] = f.read() if isinstance(_snake_case, _snake_case ): snake_case__ : List[Any] = ffmpeg_read(_snake_case, self.feature_extractor.sampling_rate ) if not isinstance(_snake_case, np.ndarray ): raise ValueError('We expect a numpy ndarray as input' ) if len(audio.shape ) != 1: raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline' ) snake_case__ : Tuple = self.feature_extractor( [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors='pt' ) snake_case__ : int = candidate_labels snake_case__ : int = [hypothesis_template.format(_snake_case ) for x in candidate_labels] snake_case__ : Optional[int] = self.tokenizer(_snake_case, return_tensors=self.framework, padding=_snake_case ) snake_case__ : List[Any] = [text_inputs] return inputs def lowercase_ ( self : Optional[int], _snake_case : Optional[Any] ) ->int: snake_case__ : Optional[int] = model_inputs.pop('candidate_labels' ) snake_case__ : str = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0], _snake_case ): snake_case__ : Optional[Any] = text_inputs[0] else: # Batching case. snake_case__ : int = text_inputs[0][0] snake_case__ : Any = self.model(**_snake_case, **_snake_case ) snake_case__ : List[Any] = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_audio, } return model_outputs def lowercase_ ( self : Union[str, Any], _snake_case : str ) ->List[str]: snake_case__ : int = model_outputs.pop('candidate_labels' ) snake_case__ : List[Any] = model_outputs['logits'][0] if self.framework == "pt": snake_case__ : Tuple = logits.softmax(dim=0 ) snake_case__ : Union[str, Any] = probs.tolist() else: raise ValueError('`tf` framework not supported.' ) snake_case__ : Union[str, Any] = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(_snake_case, _snake_case ), key=lambda _snake_case : -x[0] ) ] return result
277
1
from __future__ import annotations a_ :List[str] = 10 def lowercase_ (A : list[int] ): snake_case__ : Any = 1 snake_case__ : Optional[int] = max(A ) while placement <= max_digit: # declare and initialize empty buckets snake_case__ : list[list] = [[] for _ in range(A )] # split list_of_ints between the buckets for i in list_of_ints: snake_case__ : Dict = int((i / placement) % RADIX ) buckets[tmp].append(A ) # put each buckets' contents into list_of_ints snake_case__ : str = 0 for b in range(A ): for i in buckets[b]: snake_case__ : str = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
277
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ : """simple docstring""" def __init__( self : Tuple, _snake_case : Any, _snake_case : int=1_3, _snake_case : Optional[int]=3_2, _snake_case : Tuple=2, _snake_case : Any=3, _snake_case : Tuple=1_6, _snake_case : Tuple=[1, 2, 1], _snake_case : Dict=[2, 2, 4], _snake_case : str=2, _snake_case : Union[str, Any]=2.0, _snake_case : Dict=True, _snake_case : Dict=0.0, _snake_case : str=0.0, _snake_case : str=0.1, _snake_case : List[str]="gelu", _snake_case : int=False, _snake_case : Optional[Any]=True, _snake_case : List[Any]=0.0_2, _snake_case : Union[str, Any]=1e-5, _snake_case : Union[str, Any]=True, _snake_case : List[Any]=None, _snake_case : Any=True, _snake_case : List[Any]=1_0, _snake_case : str=8, ) ->Union[str, Any]: snake_case__ : Any = parent snake_case__ : Tuple = batch_size snake_case__ : Tuple = image_size snake_case__ : Any = patch_size snake_case__ : Optional[int] = num_channels snake_case__ : Tuple = embed_dim snake_case__ : Any = depths snake_case__ : Any = num_heads snake_case__ : List[str] = window_size snake_case__ : Dict = mlp_ratio snake_case__ : Optional[int] = qkv_bias snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : Union[str, Any] = drop_path_rate snake_case__ : str = hidden_act snake_case__ : Union[str, Any] = use_absolute_embeddings snake_case__ : Union[str, Any] = patch_norm snake_case__ : Any = layer_norm_eps snake_case__ : Tuple = initializer_range snake_case__ : Dict = is_training snake_case__ : Any = scope snake_case__ : Optional[Any] = use_labels snake_case__ : str = type_sequence_label_size snake_case__ : List[Any] = encoder_stride def lowercase_ ( self : Tuple ) ->str: snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: snake_case__ : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) snake_case__ : Any = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Optional[int] ) ->Optional[int]: return SwinvaConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, ) def lowercase_ ( self : Optional[int], _snake_case : str, _snake_case : List[str], _snake_case : int ) ->Dict: snake_case__ : List[Any] = SwinvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = model(_snake_case ) snake_case__ : List[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case__ : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def lowercase_ ( self : Optional[Any], _snake_case : Any, _snake_case : List[str], _snake_case : Dict ) ->List[Any]: snake_case__ : List[str] = SwinvaForMaskedImageModeling(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Union[str, Any] = model(_snake_case ) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images snake_case__ : Optional[Any] = 1 snake_case__ : Optional[int] = SwinvaForMaskedImageModeling(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case__ : Any = model(_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase_ ( self : List[str], _snake_case : int, _snake_case : List[Any], _snake_case : Optional[int] ) ->Any: snake_case__ : Tuple = self.type_sequence_label_size snake_case__ : int = SwinvaForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = model(_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def lowercase_ ( self : Any ) ->Dict: snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : List[str] = config_and_inputs snake_case__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Union[str, Any] ) ->Dict: snake_case__ : Optional[int] = SwinvaModelTester(self ) snake_case__ : int = ConfigTester(self, config_class=_snake_case, embed_dim=3_7 ) def lowercase_ ( self : Tuple ) ->int: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase_ ( self : Any ) ->str: snake_case__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def lowercase_ ( self : Any ) ->Union[str, Any]: pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def lowercase_ ( self : str ) ->Union[str, Any]: pass def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: snake_case__ , snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Union[str, Any] = model_class(_snake_case ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) snake_case__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_snake_case, nn.Linear ) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(_snake_case ) snake_case__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1], _snake_case ) def lowercase_ ( self : str ) ->Union[str, Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True for model_class in self.all_model_classes: snake_case__ : str = True snake_case__ : Union[str, Any] = False snake_case__ : Tuple = True snake_case__ : int = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : List[str] = outputs.attentions snake_case__ : List[Any] = len(self.model_tester.depths ) self.assertEqual(len(_snake_case ), _snake_case ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case__ : str = True snake_case__ : Tuple = config.window_size**2 snake_case__ : Optional[int] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : str = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Tuple = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) snake_case__ : Optional[Any] = len(_snake_case ) # Check attention is always last and order is fine snake_case__ : Optional[int] = True snake_case__ : Dict = True snake_case__ : List[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) if hasattr(self.model_tester, 'num_hidden_states_types' ): snake_case__ : str = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states snake_case__ : Dict = 2 self.assertEqual(out_len + added_hidden_states, len(_snake_case ) ) snake_case__ : Any = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(self_attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) def lowercase_ ( self : Dict, _snake_case : Tuple, _snake_case : Any, _snake_case : int, _snake_case : Optional[int] ) ->str: snake_case__ : Dict = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : List[Any] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Dict = outputs.hidden_states snake_case__ : int = getattr( self.model_tester, 'expected_num_hidden_layers', len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_snake_case ), _snake_case ) # Swinv2 has a different seq_length snake_case__ : int = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) snake_case__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(_snake_case ), _snake_case ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = reshaped_hidden_states[0].shape snake_case__ : Any = ( reshaped_hidden_states[0].view(_snake_case, _snake_case, height * width ).permute(0, 2, 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def lowercase_ ( self : str ) ->List[Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case__ : Optional[int] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : Dict = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) def lowercase_ ( self : List[str] ) ->str: snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[str] = 3 snake_case__ : Union[str, Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Tuple = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case__ : Optional[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case__ : int = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case ) def lowercase_ ( self : List[Any] ) ->str: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def lowercase_ ( self : str ) ->Union[str, Any]: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Dict = SwinvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def lowercase_ ( self : Optional[int] ) ->List[str]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = _config_zero_init(_snake_case ) for model_class in self.all_model_classes: snake_case__ : List[str] = model_class(config=_snake_case ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=F'''Parameter {name} of model {model_class} seems not properly initialized''', ) @require_vision @require_torch class snake_case__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowercase_ ( self : Union[str, Any] ) ->List[str]: return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def lowercase_ ( self : int ) ->List[Any]: snake_case__ : Any = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( _snake_case ) snake_case__ : int = self.default_image_processor snake_case__ : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case__ : Optional[Any] = image_processor(images=_snake_case, return_tensors='pt' ).to(_snake_case ) # forward pass with torch.no_grad(): snake_case__ : List[str] = model(**_snake_case ) # verify the logits snake_case__ : int = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _snake_case ) snake_case__ : Optional[int] = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _snake_case, atol=1e-4 ) )
277
1
a_ :Union[str, Any] = 8.3_14_45_98 def lowercase_ (A : float , A : float ): if temperature < 0: raise Exception('Temperature cannot be less than 0 K' ) if molar_mass <= 0: raise Exception('Molar mass cannot be less than or equal to 0 kg/mol' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ :Optional[int] = 300 a_ :List[Any] = 28 a_ :Union[str, Any] = rms_speed_of_molecule(temperature, molar_mass) print(F"""Vrms of Nitrogen gas at 300 K is {vrms} m/s""")
277
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class snake_case__ ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[int], _snake_case : List[Any], _snake_case : str=7, _snake_case : Tuple=3, _snake_case : List[str]=3_0, _snake_case : Tuple=4_0_0, _snake_case : Any=True, _snake_case : List[Any]=None, _snake_case : int=0.9, _snake_case : Optional[Any]=None, _snake_case : str=True, _snake_case : Union[str, Any]=[0.5, 0.5, 0.5], _snake_case : Union[str, Any]=[0.5, 0.5, 0.5], ) ->List[Any]: snake_case__ : int = size if size is not None else {'shortest_edge': 3_0} snake_case__ : Tuple = crop_size if crop_size is not None else {'height': 3_0, 'width': 3_0} snake_case__ : Union[str, Any] = parent snake_case__ : Dict = batch_size snake_case__ : int = num_channels snake_case__ : Tuple = min_resolution snake_case__ : Any = max_resolution snake_case__ : List[Any] = do_resize_and_center_crop snake_case__ : str = size snake_case__ : str = crop_pct snake_case__ : List[str] = crop_size snake_case__ : Optional[int] = do_normalize snake_case__ : Tuple = image_mean snake_case__ : Tuple = image_std def lowercase_ ( self : Optional[int] ) ->int: return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class snake_case__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = PoolFormerImageProcessor if is_vision_available() else None def lowercase_ ( self : Union[str, Any] ) ->Dict: snake_case__ : Union[str, Any] = PoolFormerImageProcessingTester(self ) @property def lowercase_ ( self : int ) ->Dict: return self.image_processor_tester.prepare_image_processor_dict() def lowercase_ ( self : Union[str, Any] ) ->Optional[int]: snake_case__ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_snake_case, 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_snake_case, 'size' ) ) self.assertTrue(hasattr(_snake_case, 'crop_pct' ) ) self.assertTrue(hasattr(_snake_case, 'do_normalize' ) ) self.assertTrue(hasattr(_snake_case, 'image_mean' ) ) self.assertTrue(hasattr(_snake_case, 'image_std' ) ) def lowercase_ ( self : List[str] ) ->List[str]: snake_case__ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'shortest_edge': 3_0} ) self.assertEqual(image_processor.crop_size, {'height': 3_0, 'width': 3_0} ) snake_case__ : int = self.image_processing_class.from_dict(self.image_processor_dict, size=4_2, crop_size=8_4 ) self.assertEqual(image_processor.size, {'shortest_edge': 4_2} ) self.assertEqual(image_processor.crop_size, {'height': 8_4, 'width': 8_4} ) def lowercase_ ( self : List[Any] ) ->List[Any]: pass def lowercase_ ( self : List[str] ) ->str: # Initialize image_processing snake_case__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case, Image.Image ) # Test not batched input snake_case__ : Optional[int] = image_processing(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), ) # Test batched snake_case__ : str = image_processing(_snake_case, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), ) def lowercase_ ( self : int ) ->List[Any]: # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : Dict = prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case, numpify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case, np.ndarray ) # Test not batched input snake_case__ : Dict = image_processing(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), ) # Test batched snake_case__ : List[Any] = image_processing(_snake_case, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), ) def lowercase_ ( self : List[str] ) ->List[str]: # Initialize image_processing snake_case__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case, torchify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case, torch.Tensor ) # Test not batched input snake_case__ : Tuple = image_processing(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), ) # Test batched snake_case__ : Optional[Any] = image_processing(_snake_case, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ), )
277
1
def lowercase_ (): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(A , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(F"""{solution() = }""")
277
from collections import deque from .hash_table import HashTable class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any], *_snake_case : Optional[Any], **_snake_case : List[Any] ) ->Optional[int]: super().__init__(*_snake_case, **_snake_case ) def lowercase_ ( self : Optional[Any], _snake_case : Tuple, _snake_case : Dict ) ->Dict: snake_case__ : int = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(_snake_case ) snake_case__ : Dict = self.values[key] def lowercase_ ( self : Any ) ->Optional[Any]: return ( sum(self.charge_factor - len(_snake_case ) for slot in self.values ) / self.size_table * self.charge_factor ) def lowercase_ ( self : Union[str, Any], _snake_case : str, _snake_case : Optional[int]=None ) ->Optional[Any]: if not ( len(self.values[key] ) == self.charge_factor and self.values.count(_snake_case ) == 0 ): return key return super()._collision_resolution(_snake_case, _snake_case )
277
1
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version a_ :Union[str, Any] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt") def lowercase_ (A : np.ndarray , A : float , A : int = 1_6_0_0_0 ): snake_case__ : Optional[int] = int(round(sample_rate * max_length ) ) if len(A ) <= sample_length: return wav snake_case__ : Any = randint(0 , len(A ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class snake_case__ : """simple docstring""" _SCREAMING_SNAKE_CASE = field(default=lowerCAmelCase_ , metadata={"""help""": """Name of a dataset from the datasets package"""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """A file containing the training audio paths and labels."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """A file containing the validation audio paths and labels."""} ) _SCREAMING_SNAKE_CASE = field( default="""train""" , metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'""" } , ) _SCREAMING_SNAKE_CASE = field( default="""validation""" , metadata={ """help""": ( """The name of the training data set split to use (via the datasets library). Defaults to 'validation'""" ) } , ) _SCREAMING_SNAKE_CASE = field( default="""audio""" , metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""} , ) _SCREAMING_SNAKE_CASE = field( default="""label""" , metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE = field( default=20 , metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""} , ) @dataclass class snake_case__ : """simple docstring""" _SCREAMING_SNAKE_CASE = field( default="""facebook/wav2vec2-base""" , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} , ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""} ) _SCREAMING_SNAKE_CASE = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Name or path of preprocessor config."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) _SCREAMING_SNAKE_CASE = field( default=lowerCAmelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def lowercase_ ( self : Optional[Any] ) ->str: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( 'The argument `--freeze_feature_extractor` is deprecated and ' 'will be removed in a future version. Use `--freeze_feature_encoder`' 'instead. Setting `freeze_feature_encoder==True`.', _snake_case, ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( 'The argument `--freeze_feature_extractor` is deprecated and ' 'should not be used in combination with `--freeze_feature_encoder`.' 'Only make use of `--freeze_feature_encoder`.' ) def lowercase_ (): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case__ : Optional[int] = 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. snake_case__ , snake_case__ , snake_case__ : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case__ , snake_case__ , snake_case__ : str = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_audio_classification' , A , A ) # 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() snake_case__ : Optional[Any] = training_args.get_process_log_level() logger.setLevel(A ) transformers.utils.logging.set_verbosity(A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. snake_case__ : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case__ : Optional[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 train from scratch.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset and prepare it for the audio classification task. snake_case__ : Dict = DatasetDict() snake_case__ : Tuple = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) snake_case__ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' 'Make sure to set `--audio_column_name` to the correct audio column - one of ' F'''{", ".join(raw_datasets["train"].column_names )}.''' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' 'Make sure to set `--label_column_name` to the correct text column - one of ' F'''{", ".join(raw_datasets["train"].column_names )}.''' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy snake_case__ : Optional[Any] = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. snake_case__ : List[str] = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) snake_case__ : Union[str, Any] = feature_extractor.model_input_names[0] def train_transforms(A : str ): snake_case__ : Optional[Any] = [] for audio in batch[data_args.audio_column_name]: snake_case__ : List[Any] = random_subsample( audio['array'] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(A ) snake_case__ : Optional[int] = feature_extractor(A , sampling_rate=feature_extractor.sampling_rate ) snake_case__ : Optional[int] = {model_input_name: inputs.get(A )} snake_case__ : Any = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(A : List[str] ): snake_case__ : Optional[Any] = [audio['array'] for audio in batch[data_args.audio_column_name]] snake_case__ : Union[str, Any] = feature_extractor(A , sampling_rate=feature_extractor.sampling_rate ) snake_case__ : List[str] = {model_input_name: inputs.get(A )} snake_case__ : List[str] = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. snake_case__ : Dict = raw_datasets['train'].features[data_args.label_column_name].names snake_case__ , snake_case__ : Tuple = {}, {} for i, label in enumerate(A ): snake_case__ : Tuple = str(A ) snake_case__ : List[str] = label # Load the accuracy metric from the datasets package snake_case__ : Union[str, Any] = evaluate.load('accuracy' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(A : int ): snake_case__ : Tuple = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=A , references=eval_pred.label_ids ) snake_case__ : List[str] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(A ) , labelaid=A , idalabel=A , finetuning_task='audio-classification' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) snake_case__ : Any = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: snake_case__ : Dict = ( raw_datasets['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(A , output_all_columns=A ) if training_args.do_eval: if data_args.max_eval_samples is not None: snake_case__ : List[Any] = ( raw_datasets['eval'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(A , output_all_columns=A ) # Initialize our trainer snake_case__ : Dict = Trainer( model=A , args=A , train_dataset=raw_datasets['train'] if training_args.do_train else None , eval_dataset=raw_datasets['eval'] if training_args.do_eval else None , compute_metrics=A , tokenizer=A , ) # Training if training_args.do_train: snake_case__ : Tuple = None if training_args.resume_from_checkpoint is not None: snake_case__ : Any = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case__ : Optional[Any] = last_checkpoint snake_case__ : int = trainer.train(resume_from_checkpoint=A ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: snake_case__ : int = trainer.evaluate() trainer.log_metrics('eval' , A ) trainer.save_metrics('eval' , A ) # Write model card and (optionally) push to hub snake_case__ : Any = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'audio-classification', 'dataset': data_args.dataset_name, 'tags': ['audio-classification'], } if training_args.push_to_hub: trainer.push_to_hub(**A ) else: trainer.create_model_card(**A ) if __name__ == "__main__": main()
277
def lowercase_ (A : Union[str, Any] , A : List[str] , A : int , A : Optional[int] ): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: snake_case__ : Union[str, Any] = mf_knapsack(i - 1 , A , A , A ) else: snake_case__ : Any = max( mf_knapsack(i - 1 , A , A , A ) , mf_knapsack(i - 1 , A , A , j - wt[i - 1] ) + val[i - 1] , ) snake_case__ : Optional[int] = val return f[i][j] def lowercase_ (A : Optional[int] , A : Union[str, Any] , A : str , A : Dict ): snake_case__ : int = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: snake_case__ : Union[str, Any] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: snake_case__ : str = dp[i - 1][w_] return dp[n][w_], dp def lowercase_ (A : int , A : list , A : list ): if not (isinstance(A , (list, tuple) ) and isinstance(A , (list, tuple) )): raise ValueError( 'Both the weights and values vectors must be either lists or tuples' ) snake_case__ : Dict = len(A ) if num_items != len(A ): snake_case__ : str = ( 'The number of weights must be the same as the number of values.\n' F'''But got {num_items} weights and {len(A )} values''' ) raise ValueError(A ) for i in range(A ): if not isinstance(wt[i] , A ): snake_case__ : Optional[int] = ( 'All weights must be integers but got weight of ' F'''type {type(wt[i] )} at index {i}''' ) raise TypeError(A ) snake_case__ , snake_case__ : Optional[int] = knapsack(A , A , A , A ) snake_case__ : set = set() _construct_solution(A , A , A , A , A ) return optimal_val, example_optional_set def lowercase_ (A : list , A : list , A : int , A : int , A : set ): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(A , A , i - 1 , A , A ) else: optimal_set.add(A ) _construct_solution(A , A , i - 1 , j - wt[i - 1] , A ) if __name__ == "__main__": a_ :Any = [3, 2, 4, 4] a_ :List[Any] = [4, 3, 2, 3] a_ :Union[str, Any] = 4 a_ :List[str] = 6 a_ :Union[str, Any] = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] a_ , a_ :List[Any] = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 a_ , a_ :Any = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
277
1
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py a_ :str = "\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n author = \"Lin, Chin-Yew and\n Och, Franz Josef\",\n booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n month = \"aug 23{--}aug 27\",\n year = \"2004\",\n address = \"Geneva, Switzerland\",\n publisher = \"COLING\",\n url = \"https://www.aclweb.org/anthology/C04-1072\",\n pages = \"501--507\",\n}\n" a_ :Optional[int] = "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n" a_ :Dict = "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n 'bleu': bleu score,\n 'precisions': geometric mean of n-gram precisions,\n 'brevity_penalty': brevity penalty,\n 'length_ratio': ratio of lengths,\n 'translation_length': translation_length,\n 'reference_length': reference_length\nExamples:\n\n >>> predictions = [\n ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample\n ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references)\n ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric(\"bleu\")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results[\"bleu\"])\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): """simple docstring""" def lowercase_ ( self : Optional[Any] ) ->Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), id='references' ), } ), codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'], reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ], ) def lowercase_ ( self : List[Any], _snake_case : List[str], _snake_case : Dict, _snake_case : Optional[int]=4, _snake_case : Optional[int]=False ) ->Optional[int]: snake_case__ : Any = compute_bleu( reference_corpus=_snake_case, translation_corpus=_snake_case, max_order=_snake_case, smooth=_snake_case ) ((snake_case__) , (snake_case__) , (snake_case__) , (snake_case__) , (snake_case__) , (snake_case__)) : Tuple = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
277
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a_ :int = { "configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :List[str] = [ "LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST", "LongT5EncoderModel", "LongT5ForConditionalGeneration", "LongT5Model", "LongT5PreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :int = [ "FlaxLongT5ForConditionalGeneration", "FlaxLongT5Model", "FlaxLongT5PreTrainedModel", ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys a_ :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
277
1
import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer a_ :Union[str, Any] = logging.get_logger(__name__) class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """AutoTokenizer""" _SCREAMING_SNAKE_CASE = ["""tokenizer"""] _SCREAMING_SNAKE_CASE = { """semantic_prompt""": 1, """coarse_prompt""": 2, """fine_prompt""": 2, } def __init__( self : Any, _snake_case : int, _snake_case : Optional[Any]=None ) ->Optional[Any]: super().__init__(_snake_case ) snake_case__ : Union[str, Any] = speaker_embeddings @classmethod def lowercase_ ( cls : Optional[int], _snake_case : Optional[int], _snake_case : Dict="speaker_embeddings_path.json", **_snake_case : Optional[Any] ) ->Dict: if speaker_embeddings_dict_path is not None: snake_case__ : Any = get_file_from_repo( _snake_case, _snake_case, subfolder=kwargs.pop('subfolder', _snake_case ), cache_dir=kwargs.pop('cache_dir', _snake_case ), force_download=kwargs.pop('force_download', _snake_case ), proxies=kwargs.pop('proxies', _snake_case ), resume_download=kwargs.pop('resume_download', _snake_case ), local_files_only=kwargs.pop('local_files_only', _snake_case ), use_auth_token=kwargs.pop('use_auth_token', _snake_case ), revision=kwargs.pop('revision', _snake_case ), ) if speaker_embeddings_path is None: logger.warning( F'''`{os.path.join(_snake_case, _snake_case )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.''' ) snake_case__ : Union[str, Any] = None else: with open(_snake_case ) as speaker_embeddings_json: snake_case__ : Union[str, Any] = json.load(_snake_case ) else: snake_case__ : Optional[Any] = None snake_case__ : Optional[int] = AutoTokenizer.from_pretrained(_snake_case, **_snake_case ) return cls(tokenizer=_snake_case, speaker_embeddings=_snake_case ) def lowercase_ ( self : Union[str, Any], _snake_case : Tuple, _snake_case : Tuple="speaker_embeddings_path.json", _snake_case : Dict="speaker_embeddings", _snake_case : bool = False, **_snake_case : int, ) ->int: if self.speaker_embeddings is not None: os.makedirs(os.path.join(_snake_case, _snake_case, 'v2' ), exist_ok=_snake_case ) snake_case__ : Optional[Any] = {} snake_case__ : Any = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": snake_case__ : Union[str, Any] = self._load_voice_preset(_snake_case ) snake_case__ : List[str] = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict['repo_or_path'], _snake_case, F'''{prompt_key}_{key}''' ), voice_preset[key], allow_pickle=_snake_case, ) snake_case__ : Dict = os.path.join(_snake_case, F'''{prompt_key}_{key}.npy''' ) snake_case__ : List[str] = tmp_dict with open(os.path.join(_snake_case, _snake_case ), 'w' ) as fp: json.dump(_snake_case, _snake_case ) super().save_pretrained(_snake_case, _snake_case, **_snake_case ) def lowercase_ ( self : int, _snake_case : str = None, **_snake_case : Dict ) ->Tuple: snake_case__ : int = self.speaker_embeddings[voice_preset] snake_case__ : Tuple = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F'''Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].''' ) snake_case__ : Dict = get_file_from_repo( self.speaker_embeddings.get('repo_or_path', '/' ), voice_preset_paths[key], subfolder=kwargs.pop('subfolder', _snake_case ), cache_dir=kwargs.pop('cache_dir', _snake_case ), force_download=kwargs.pop('force_download', _snake_case ), proxies=kwargs.pop('proxies', _snake_case ), resume_download=kwargs.pop('resume_download', _snake_case ), local_files_only=kwargs.pop('local_files_only', _snake_case ), use_auth_token=kwargs.pop('use_auth_token', _snake_case ), revision=kwargs.pop('revision', _snake_case ), ) if path is None: raise ValueError( F'''`{os.path.join(self.speaker_embeddings.get("repo_or_path", "/" ), voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.''' ) snake_case__ : Tuple = np.load(_snake_case ) return voice_preset_dict def lowercase_ ( self : Optional[int], _snake_case : Optional[dict] = None ) ->Any: for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F'''Voice preset unrecognized, missing {key} as a key.''' ) if not isinstance(voice_preset[key], np.ndarray ): raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) def __call__( self : Optional[Any], _snake_case : List[Any]=None, _snake_case : Optional[Any]=None, _snake_case : int="pt", _snake_case : Any=2_5_6, _snake_case : str=False, _snake_case : Tuple=True, _snake_case : Dict=False, **_snake_case : List[str], ) ->Tuple: if voice_preset is not None and not isinstance(_snake_case, _snake_case ): if ( isinstance(_snake_case, _snake_case ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): snake_case__ : Dict = self._load_voice_preset(_snake_case ) else: if isinstance(_snake_case, _snake_case ) and not voice_preset.endswith('.npz' ): snake_case__ : Union[str, Any] = voice_preset + '.npz' snake_case__ : List[Any] = np.load(_snake_case ) if voice_preset is not None: self._validate_voice_preset_dict(_snake_case, **_snake_case ) snake_case__ : Union[str, Any] = BatchFeature(data=_snake_case, tensor_type=_snake_case ) snake_case__ : Any = self.tokenizer( _snake_case, return_tensors=_snake_case, padding='max_length', max_length=_snake_case, return_attention_mask=_snake_case, return_token_type_ids=_snake_case, add_special_tokens=_snake_case, **_snake_case, ) if voice_preset is not None: snake_case__ : Optional[Any] = voice_preset return encoded_text
277
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowercase_ (A : List[str] ): snake_case__ : Tuple = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(A , A ) def lowercase_ (A : str ): snake_case__ , snake_case__ : Union[str, Any] = emb.weight.shape snake_case__ : str = nn.Linear(A , A , bias=A ) snake_case__ : str = emb.weight.data return lin_layer def lowercase_ (A : Optional[int] , A : Union[str, Any]=None ): snake_case__ : Any = {} for old_key in state_dict.keys(): snake_case__ : Tuple = old_key if "moe_layer.experts." in key: if expert_idx is not None: snake_case__ : int = key.replace('moe_layer.experts.0' , F'''ffn.experts.expert_{expert_idx}''' ) else: snake_case__ : Any = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: snake_case__ : Dict = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: snake_case__ : str = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: snake_case__ : str = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: snake_case__ : Tuple = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: snake_case__ : Tuple = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: snake_case__ : Optional[int] = key.replace('final_layer_norm' , 'ff_layer_norm' ) snake_case__ : Dict = state_dict[old_key] return new_dict def lowercase_ (A : List[Any] , A : Tuple , A : List[Any] , A : List[str] , A : str = WEIGHTS_NAME ): snake_case__ : Dict = [] snake_case__ : str = 0 os.makedirs(A , exist_ok=A ) for expert in range(A ): snake_case__ : Tuple = switch_checkpoint_path + F'''-rank-{expert}.pt''' if os.path.isfile(A ): snake_case__ : Optional[Any] = torch.load(A )['model'] remove_ignore_keys_(A ) snake_case__ : Optional[Any] = rename_fairseq_keys(A , A ) snake_case__ : Dict = os.path.join( A , weights_name.replace('.bin' , F'''-{len(A )+1:05d}-of-???.bin''' ) ) torch.save(A , A ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A )[0]].dtype ) # Add the last block snake_case__ : Tuple = os.path.join(A , weights_name.replace('.bin' , F'''-{len(A )+1:05d}-of-???.bin''' ) ) snake_case__ : Union[str, Any] = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(A ) snake_case__ : str = rename_fairseq_keys(A , A ) snake_case__ : Any = shared_weights['decoder.embed_tokens.weight'] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A ) == 1: snake_case__ : Any = os.path.join(A , A ) torch.save(A , A ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A , A ) # Otherwise, let's build the index snake_case__ : Tuple = {} for idx, shard in enumerate(A ): snake_case__ : Optional[int] = weights_name.replace('.bin' , F'''-{idx+1:05d}-of-{len(A ):05d}.bin''' ) snake_case__ : List[Any] = os.path.join(A , weights_name.replace('.bin' , F'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(A , os.path.join(A , A ) ) for key in shard: snake_case__ : Any = shard_file # Add the metadata snake_case__ : int = {'total_size': total_size} snake_case__ : Dict = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(A , A ) , 'w' , encoding='utf-8' ) as f: snake_case__ : Any = json.dumps(A , indent=2 , sort_keys=A ) + '\n' f.write(A ) return metadata, index if __name__ == "__main__": a_ :int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--nllb_moe_checkpoint_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b", type=str, required=False, help="Path to the output pytorch model.", ) a_ :Optional[Any] = parser.parse_args() a_ , a_ :Optional[Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) a_ :List[str] = NllbMoeConfig.from_pretrained( "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) a_ :int = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("Done") model.save_pretrained(args.pytorch_dump_folder_path)
277
1
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler a_ :Any = 16 a_ :Any = 32 def lowercase_ (A : Accelerator , A : int = 1_6 , A : str = "bert-base-cased" ): snake_case__ : Tuple = AutoTokenizer.from_pretrained(A ) snake_case__ : Union[str, Any] = load_dataset('glue' , 'mrpc' ) def tokenize_function(A : List[Any] ): # max_length=None => use the model max length (it's actually the default) snake_case__ : Union[str, Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=A , max_length=A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset snake_case__ : List[str] = datasets.map( A , batched=A , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=A ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case__ : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(A : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A , padding='max_length' , max_length=1_2_8 , return_tensors='pt' ) return tokenizer.pad(A , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. snake_case__ : List[str] = DataLoader( tokenized_datasets['train'] , shuffle=A , collate_fn=A , batch_size=A ) snake_case__ : Optional[Any] = DataLoader( tokenized_datasets['validation'] , shuffle=A , collate_fn=A , batch_size=A ) return train_dataloader, eval_dataloader def lowercase_ (A : Dict , A : List[str] ): # Initialize accelerator snake_case__ : Tuple = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case__ : Tuple = config['lr'] snake_case__ : List[Any] = int(config['num_epochs'] ) snake_case__ : Optional[int] = int(config['seed'] ) snake_case__ : Any = int(config['batch_size'] ) snake_case__ : List[str] = args.model_name_or_path set_seed(A ) snake_case__ , snake_case__ : Optional[Any] = get_dataloaders(A , A , A ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case__ : Any = AutoModelForSequenceClassification.from_pretrained(A , return_dict=A ) # Instantiate optimizer snake_case__ : List[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) snake_case__ : Optional[int] = optimizer_cls(params=model.parameters() , lr=A ) if accelerator.state.deepspeed_plugin is not None: snake_case__ : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: snake_case__ : int = 1 snake_case__ : Any = (len(A ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): snake_case__ : str = get_linear_schedule_with_warmup( optimizer=A , num_warmup_steps=0 , num_training_steps=A , ) else: snake_case__ : List[str] = DummyScheduler(A , total_num_steps=A , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = accelerator.prepare( A , A , A , A , A ) # We need to keep track of how many total steps we have iterated over snake_case__ : List[str] = 0 # We also need to keep track of the stating epoch so files are named properly snake_case__ : Union[str, Any] = 0 # Now we train the model snake_case__ : Any = evaluate.load('glue' , 'mrpc' ) snake_case__ : List[str] = 0 snake_case__ : List[str] = {} for epoch in range(A , A ): model.train() for step, batch in enumerate(A ): snake_case__ : str = model(**A ) snake_case__ : Dict = outputs.loss snake_case__ : Dict = loss / gradient_accumulation_steps accelerator.backward(A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() snake_case__ : List[Any] = 0 for step, batch in enumerate(A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case__ : Union[str, Any] = model(**A ) snake_case__ : Tuple = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times snake_case__ , snake_case__ : int = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(A ) - 1: snake_case__ : int = predictions[: len(eval_dataloader.dataset ) - samples_seen] snake_case__ : List[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=A , references=A , ) snake_case__ : Optional[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , A ) snake_case__ : Optional[Any] = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: snake_case__ : List[Any] = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(A , A ) def lowercase_ (): snake_case__ : List[Any] = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=A , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=A , ) parser.add_argument( '--output_dir' , type=A , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=A , default=A , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=A , default=3 , help='Number of train epochs.' , ) snake_case__ : str = parser.parse_args() snake_case__ : Dict = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 4_2, 'batch_size': 1_6} training_function(A , A ) if __name__ == "__main__": main()
277
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a_ :Optional[Any] = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :str = ["ReformerTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :int = ["ReformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :List[str] = [ "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ReformerAttention", "ReformerForMaskedLM", "ReformerForQuestionAnswering", "ReformerForSequenceClassification", "ReformerLayer", "ReformerModel", "ReformerModelWithLMHead", "ReformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys a_ :Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
277
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: a_ :str = None a_ :Optional[int] = logging.get_logger(__name__) a_ :Union[str, Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} a_ :Optional[Any] = { "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } a_ :Optional[Any] = { "moussaKam/mbarthez": 1_024, "moussaKam/barthez": 1_024, "moussaKam/barthez-orangesum-title": 1_024, } a_ :List[str] = "▁" class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE = BarthezTokenizer def __init__( self : Any, _snake_case : Optional[int]=None, _snake_case : Optional[int]=None, _snake_case : int="<s>", _snake_case : List[str]="</s>", _snake_case : Optional[int]="</s>", _snake_case : Optional[Any]="<s>", _snake_case : Any="<unk>", _snake_case : Optional[Any]="<pad>", _snake_case : Any="<mask>", **_snake_case : int, ) ->Dict: # Mask token behave like a normal word, i.e. include the space before it snake_case__ : Dict = AddedToken(_snake_case, lstrip=_snake_case, rstrip=_snake_case ) if isinstance(_snake_case, _snake_case ) else mask_token super().__init__( _snake_case, tokenizer_file=_snake_case, bos_token=_snake_case, eos_token=_snake_case, unk_token=_snake_case, sep_token=_snake_case, cls_token=_snake_case, pad_token=_snake_case, mask_token=_snake_case, **_snake_case, ) snake_case__ : List[Any] = vocab_file snake_case__ : Optional[Any] = False if not self.vocab_file else True def lowercase_ ( self : Optional[int], _snake_case : List[int], _snake_case : Optional[List[int]] = None ) ->List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case__ : Dict = [self.cls_token_id] snake_case__ : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowercase_ ( self : List[str], _snake_case : List[int], _snake_case : Optional[List[int]] = None ) ->List[int]: snake_case__ : List[str] = [self.sep_token_id] snake_case__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : Union[str, Any], _snake_case : str, _snake_case : Optional[str] = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_snake_case ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return snake_case__ : Any = os.path.join( _snake_case, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_snake_case ): copyfile(self.vocab_file, _snake_case ) return (out_vocab_file,)
277
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 a_ :Any = random.Random() def lowercase_ (A : int , A : Union[str, Any]=1.0 , A : List[str]=None , A : Any=None ): if rng is None: snake_case__ : List[str] = global_rng snake_case__ : int = [] 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 ): """simple docstring""" def __init__( self : Optional[Any], _snake_case : List[str], _snake_case : Tuple=7, _snake_case : Union[str, Any]=4_0_0, _snake_case : Any=2_0_0_0, _snake_case : Dict=1, _snake_case : Optional[Any]=0.0, _snake_case : List[Any]=1_6_0_0_0, _snake_case : List[Any]=True, _snake_case : List[Any]=8_0, _snake_case : Dict=1_6, _snake_case : str=6_4, _snake_case : Tuple="hann_window", _snake_case : Union[str, Any]=8_0, _snake_case : Optional[Any]=7_6_0_0, _snake_case : str=1e-10, _snake_case : Any=True, ) ->Union[str, Any]: snake_case__ : Optional[int] = parent snake_case__ : Optional[Any] = batch_size snake_case__ : List[Any] = min_seq_length snake_case__ : List[Any] = max_seq_length snake_case__ : Any = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case__ : Tuple = feature_size snake_case__ : List[Any] = padding_value snake_case__ : Any = sampling_rate snake_case__ : Dict = do_normalize snake_case__ : Union[str, Any] = num_mel_bins snake_case__ : Any = hop_length snake_case__ : Any = win_length snake_case__ : Any = win_function snake_case__ : Optional[int] = fmin snake_case__ : int = fmax snake_case__ : Union[str, Any] = mel_floor snake_case__ : Union[str, Any] = return_attention_mask def lowercase_ ( self : Optional[int] ) ->List[str]: 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 : Any, _snake_case : Optional[Any]=False, _snake_case : List[str]=False ) ->Union[str, Any]: def _flatten(_snake_case : List[str] ): return list(itertools.chain(*_snake_case ) ) if equal_length: snake_case__ : Any = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size snake_case__ : 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: snake_case__ : Any = [np.asarray(_snake_case ) for x in speech_inputs] return speech_inputs def lowercase_ ( self : Union[str, Any], _snake_case : str=False, _snake_case : Dict=False ) ->List[str]: if equal_length: snake_case__ : Optional[Any] = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case__ : List[str] = [ 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: snake_case__ : int = [np.asarray(_snake_case ) for x in speech_inputs] return speech_inputs @require_torch class snake_case__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = SpeechTaFeatureExtractor def lowercase_ ( self : int ) ->Union[str, Any]: snake_case__ : List[str] = SpeechTaFeatureExtractionTester(self ) def lowercase_ ( self : Any, _snake_case : Dict ) ->Any: self.assertTrue(np.all(np.mean(_snake_case, axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(_snake_case, axis=0 ) - 1 ) < 1e-3 ) ) def lowercase_ ( self : List[Any] ) ->Union[str, Any]: # Tests that all call wrap to encode_plus and batch_encode_plus snake_case__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case__ : int = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : Tuple = [np.asarray(_snake_case ) for speech_input in speech_inputs] # Test not batched input snake_case__ : str = feat_extract(speech_inputs[0], return_tensors='np' ).input_values snake_case__ : List[str] = feat_extract(np_speech_inputs[0], return_tensors='np' ).input_values self.assertTrue(np.allclose(_snake_case, _snake_case, atol=1e-3 ) ) # Test batched snake_case__ : Any = feat_extract(_snake_case, return_tensors='np' ).input_values snake_case__ : Union[str, Any] = feat_extract(_snake_case, return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(_snake_case, _snake_case ): self.assertTrue(np.allclose(_snake_case, _snake_case, atol=1e-3 ) ) def lowercase_ ( self : int ) ->Optional[int]: snake_case__ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case__ : Tuple = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : int = ['longest', 'max_length', 'do_not_pad'] snake_case__ : List[str] = [None, 1_6_0_0, None] for max_length, padding in zip(_snake_case, _snake_case ): snake_case__ : Optional[int] = feat_extract(_snake_case, padding=_snake_case, max_length=_snake_case, return_tensors='np' ) snake_case__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def lowercase_ ( self : Union[str, Any] ) ->Optional[Any]: snake_case__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case__ : Tuple = range(8_0_0, 1_4_0_0, 2_0_0 ) snake_case__ : Optional[Any] = [floats_list((1, x) )[0] for x in lengths] snake_case__ : Union[str, Any] = ['longest', 'max_length', 'do_not_pad'] snake_case__ : str = [None, 1_6_0_0, None] for max_length, padding in zip(_snake_case, _snake_case ): snake_case__ : List[str] = feat_extract(_snake_case, max_length=_snake_case, padding=_snake_case ) snake_case__ : Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def lowercase_ ( self : List[Any] ) ->Optional[Any]: snake_case__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case__ : str = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : Optional[Any] = feat_extract( _snake_case, truncation=_snake_case, max_length=1_0_0_0, padding='max_length', return_tensors='np' ) snake_case__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def lowercase_ ( self : int ) ->Union[str, Any]: snake_case__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case__ : Dict = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : str = feat_extract( _snake_case, truncation=_snake_case, max_length=1_0_0_0, padding='longest', return_tensors='np' ) snake_case__ : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) 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, 1_0_0_0) ) snake_case__ : Tuple = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : List[str] = feat_extract( _snake_case, truncation=_snake_case, max_length=2_0_0_0, padding='longest', return_tensors='np' ) snake_case__ : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) 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, 1_2_0_0) ) def lowercase_ ( self : List[str] ) ->Dict: snake_case__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case__ : List[Any] = np.random.rand(1_0_0 ).astype(np.floataa ) snake_case__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case__ : int = feature_extractor.pad([{'input_values': inputs}], return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) 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 : Optional[int] ) ->Optional[Any]: # Tests that all call wrap to encode_plus and batch_encode_plus snake_case__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case__ : List[Any] = [floats_list((1, x) )[0] for x in range(8_0_0, 1_4_0_0, 2_0_0 )] snake_case__ : Dict = [np.asarray(_snake_case ) for speech_input in speech_inputs] # Test feature size snake_case__ : Optional[int] = feature_extractor(audio_target=_snake_case, padding=_snake_case, 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 snake_case__ : Dict = feature_extractor(speech_inputs[0], return_tensors='np' ).input_values snake_case__ : Any = feature_extractor(np_speech_inputs[0], return_tensors='np' ).input_values self.assertTrue(np.allclose(_snake_case, _snake_case, atol=1e-3 ) ) # Test batched snake_case__ : Dict = feature_extractor(_snake_case, return_tensors='np' ).input_values snake_case__ : Dict = feature_extractor(_snake_case, return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(_snake_case, _snake_case ): self.assertTrue(np.allclose(_snake_case, _snake_case, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case__ : Optional[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] snake_case__ : int = np.asarray(_snake_case ) snake_case__ : Union[str, Any] = feature_extractor(_snake_case, return_tensors='np' ).input_values snake_case__ : Union[str, Any] = feature_extractor(_snake_case, return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(_snake_case, _snake_case ): self.assertTrue(np.allclose(_snake_case, _snake_case, atol=1e-3 ) ) def lowercase_ ( self : Union[str, Any] ) ->str: snake_case__ : int = self.feat_extract_tester.prepare_inputs_for_target() snake_case__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case__ : Optional[Any] = feat_extract.model_input_names[0] snake_case__ : Tuple = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_snake_case ) == len(_snake_case ) for x, y in zip(_snake_case, processed_features[input_name] ) ) ) snake_case__ : int = self.feat_extract_tester.prepare_inputs_for_target(equal_length=_snake_case ) snake_case__ : Union[str, Any] = BatchFeature({input_name: speech_inputs}, tensor_type='np' ) snake_case__ : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: snake_case__ : List[str] = 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[str] ) ->Any: snake_case__ : int = self.feat_extract_tester.prepare_inputs_for_target(equal_length=_snake_case ) snake_case__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case__ : Tuple = feat_extract.model_input_names[0] snake_case__ : List[Any] = BatchFeature({input_name: speech_inputs}, tensor_type='pt' ) snake_case__ : Tuple = processed_features[input_name] if len(batch_features_input.shape ) < 3: 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 : Optional[int] ) ->Tuple: snake_case__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) snake_case__ : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_target() snake_case__ : Optional[Any] = feat_extract.model_input_names[0] snake_case__ : List[str] = BatchFeature({input_name: speech_inputs} ) snake_case__ : int = feat_extract.num_mel_bins # hack! snake_case__ : Tuple = feat_extract.pad(_snake_case, padding='longest', return_tensors='np' )[input_name] snake_case__ : Union[str, Any] = feat_extract.pad(_snake_case, 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 ) ->Any: snake_case__ : Any = self.feat_extract_dict snake_case__ : List[Any] = True snake_case__ : Union[str, Any] = self.feature_extraction_class(**_snake_case ) snake_case__ : Any = self.feat_extract_tester.prepare_inputs_for_target() snake_case__ : List[Any] = [len(_snake_case ) for x in speech_inputs] snake_case__ : Union[str, Any] = feat_extract.model_input_names[0] snake_case__ : Optional[int] = BatchFeature({input_name: speech_inputs} ) snake_case__ : List[str] = feat_extract.num_mel_bins # hack! snake_case__ : str = feat_extract.pad(_snake_case, padding='longest', return_tensors='np' ) self.assertIn('attention_mask', _snake_case ) self.assertListEqual(list(processed.attention_mask.shape ), list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist(), _snake_case ) def lowercase_ ( self : Optional[int] ) ->str: snake_case__ : int = self.feat_extract_dict snake_case__ : List[str] = True snake_case__ : Tuple = self.feature_extraction_class(**_snake_case ) snake_case__ : List[str] = self.feat_extract_tester.prepare_inputs_for_target() snake_case__ : str = [len(_snake_case ) for x in speech_inputs] snake_case__ : Optional[Any] = feat_extract.model_input_names[0] snake_case__ : Optional[int] = BatchFeature({input_name: speech_inputs} ) snake_case__ : Optional[Any] = min(_snake_case ) snake_case__ : Union[str, Any] = feat_extract.num_mel_bins # hack! snake_case__ : Tuple = feat_extract.pad( _snake_case, padding='max_length', max_length=_snake_case, truncation=_snake_case, return_tensors='np' ) self.assertIn('attention_mask', _snake_case ) 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 : List[Any], _snake_case : Optional[int] ) ->Optional[Any]: from datasets import load_dataset snake_case__ : str = load_dataset('hf-internal-testing/librispeech_asr_dummy', 'clean', split='validation' ) # automatic decoding with librispeech snake_case__ : Dict = ds.sort('id' ).select(range(_snake_case ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def lowercase_ ( self : str ) ->str: # fmt: off snake_case__ : List[Any] = torch.tensor( [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03, 3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03, 2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04, 4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03, 7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04, 4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03] ) # fmt: on snake_case__ : Union[str, Any] = self._load_datasamples(1 ) snake_case__ : Optional[int] = SpeechTaFeatureExtractor() snake_case__ : List[Any] = feature_extractor(_snake_case, return_tensors='pt' ).input_values self.assertEquals(input_values.shape, (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0], _snake_case, atol=1e-6 ) ) def lowercase_ ( self : Any ) ->str: # fmt: off snake_case__ : Optional[Any] = torch.tensor( [-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7, -3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6, -3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1, -3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8] ) # fmt: on snake_case__ : List[str] = self._load_datasamples(1 ) snake_case__ : str = SpeechTaFeatureExtractor() snake_case__ : Optional[Any] = feature_extractor(audio_target=_snake_case, return_tensors='pt' ).input_values self.assertEquals(input_values.shape, (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0], _snake_case, atol=1e-4 ) )
277
1
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal a_ :int = datasets.utils.logging.get_logger(__name__) a_ :Union[str, Any] = ["names", "prefix"] a_ :str = ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"] a_ :Optional[int] = ["encoding_errors", "on_bad_lines"] a_ :Tuple = ["date_format"] @dataclass class snake_case__ ( datasets.BuilderConfig ): """simple docstring""" _SCREAMING_SNAKE_CASE = "," _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = "infer" _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = "." _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = '"' _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = 10000 _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = "strict" _SCREAMING_SNAKE_CASE = "error" _SCREAMING_SNAKE_CASE = None def lowercase_ ( self : Dict ) ->str: if self.delimiter is not None: snake_case__ : Optional[int] = self.delimiter if self.column_names is not None: snake_case__ : Optional[Any] = self.column_names @property def lowercase_ ( self : Optional[Any] ) ->List[Any]: snake_case__ : Any = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig(), _snake_case ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class snake_case__ ( datasets.ArrowBasedBuilder ): """simple docstring""" _SCREAMING_SNAKE_CASE = CsvConfig def lowercase_ ( self : Union[str, Any] ) ->Any: return datasets.DatasetInfo(features=self.config.features ) def lowercase_ ( self : int, _snake_case : Optional[Any] ) ->Any: if not self.config.data_files: raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) snake_case__ : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_snake_case, (str, list, tuple) ): snake_case__ : List[Any] = data_files if isinstance(_snake_case, _snake_case ): snake_case__ : List[Any] = [files] snake_case__ : Optional[int] = [dl_manager.iter_files(_snake_case ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'files': files} )] snake_case__ : Tuple = [] for split_name, files in data_files.items(): if isinstance(_snake_case, _snake_case ): snake_case__ : Any = [files] snake_case__ : int = [dl_manager.iter_files(_snake_case ) for file in files] splits.append(datasets.SplitGenerator(name=_snake_case, gen_kwargs={'files': files} ) ) return splits def lowercase_ ( self : List[str], _snake_case : pa.Table ) ->pa.Table: if self.config.features is not None: snake_case__ : Union[str, Any] = self.config.features.arrow_schema if all(not require_storage_cast(_snake_case ) for feature in self.config.features.values() ): # cheaper cast snake_case__ : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema], schema=_snake_case ) else: # more expensive cast; allows str <-> int/float or str to Audio for example snake_case__ : List[str] = table_cast(_snake_case, _snake_case ) return pa_table def lowercase_ ( self : str, _snake_case : List[str] ) ->List[Any]: snake_case__ : List[Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str snake_case__ : List[Any] = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_snake_case ) else object for name, dtype, feature in zip(schema.names, schema.types, self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_snake_case ) ): snake_case__ : Any = pd.read_csv(_snake_case, iterator=_snake_case, dtype=_snake_case, **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_snake_case ): snake_case__ : Optional[Any] = pa.Table.from_pandas(_snake_case ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_snake_case ) except ValueError as e: logger.error(F'''Failed to read file \'{file}\' with error {type(_snake_case )}: {e}''' ) raise
277
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """philschmid/bart-large-cnn-samsum""" _SCREAMING_SNAKE_CASE = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) _SCREAMING_SNAKE_CASE = """summarizer""" _SCREAMING_SNAKE_CASE = AutoTokenizer _SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM _SCREAMING_SNAKE_CASE = ["""text"""] _SCREAMING_SNAKE_CASE = ["""text"""] def lowercase_ ( self : Optional[Any], _snake_case : str ) ->Any: return self.pre_processor(_snake_case, return_tensors='pt', truncation=_snake_case ) def lowercase_ ( self : int, _snake_case : List[Any] ) ->Any: return self.model.generate(**_snake_case )[0] def lowercase_ ( self : int, _snake_case : int ) ->str: return self.pre_processor.decode(_snake_case, skip_special_tokens=_snake_case, clean_up_tokenization_spaces=_snake_case )
277
1
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ : """simple docstring""" def __init__( self : int, _snake_case : str, _snake_case : int=1_3, _snake_case : List[str]=3_2, _snake_case : Any=3, _snake_case : Optional[int]=4, _snake_case : List[Any]=[1_0, 2_0, 3_0, 4_0], _snake_case : Optional[int]=[2, 2, 3, 2], _snake_case : Any=True, _snake_case : Union[str, Any]=True, _snake_case : Any=3_7, _snake_case : str="gelu", _snake_case : List[Any]=1_0, _snake_case : Optional[Any]=0.0_2, _snake_case : str=["stage2", "stage3", "stage4"], _snake_case : Tuple=[2, 3, 4], _snake_case : Dict=None, ) ->Optional[Any]: snake_case__ : int = parent snake_case__ : List[Any] = batch_size snake_case__ : Dict = image_size snake_case__ : Tuple = num_channels snake_case__ : str = num_stages snake_case__ : Any = hidden_sizes snake_case__ : Any = depths snake_case__ : int = is_training snake_case__ : Any = use_labels snake_case__ : Any = intermediate_size snake_case__ : int = hidden_act snake_case__ : List[Any] = num_labels snake_case__ : Dict = initializer_range snake_case__ : Dict = out_features snake_case__ : Optional[int] = out_indices snake_case__ : Optional[Any] = scope def lowercase_ ( self : int ) ->int: snake_case__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: snake_case__ : List[Any] = ids_tensor([self.batch_size], self.num_labels ) snake_case__ : Tuple = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Optional[int] ) ->Union[str, Any]: return ConvNextConfig( num_channels=self.num_channels, hidden_sizes=self.hidden_sizes, depths=self.depths, num_stages=self.num_stages, hidden_act=self.hidden_act, is_decoder=_snake_case, initializer_range=self.initializer_range, out_features=self.out_features, out_indices=self.out_indices, num_labels=self.num_labels, ) def lowercase_ ( self : Any, _snake_case : Optional[Any], _snake_case : Optional[int], _snake_case : Optional[Any] ) ->Dict: snake_case__ : Union[str, Any] = ConvNextModel(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : List[Any] = model(_snake_case ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2), ) def lowercase_ ( self : Tuple, _snake_case : str, _snake_case : Dict, _snake_case : Optional[int] ) ->List[Any]: snake_case__ : Optional[int] = ConvNextForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = model(_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def lowercase_ ( self : Dict, _snake_case : Dict, _snake_case : Any, _snake_case : Dict ) ->Optional[int]: snake_case__ : Dict = ConvNextBackbone(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = model(_snake_case ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ), len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ), len(config.out_features ) ) self.parent.assertListEqual(model.channels, config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case__ : str = None snake_case__ : Optional[Any] = ConvNextBackbone(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Dict = model(_snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ), 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ), [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ), 1 ) self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]] ) def lowercase_ ( self : List[str] ) ->Optional[Any]: snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = config_and_inputs snake_case__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Tuple ) ->str: snake_case__ : List[Any] = ConvNextModelTester(self ) snake_case__ : Union[str, Any] = ConfigTester(self, config_class=_snake_case, has_text_modality=_snake_case, hidden_size=3_7 ) def lowercase_ ( self : Union[str, Any] ) ->int: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase_ ( self : Any ) ->Tuple: return @unittest.skip(reason='ConvNext does not use inputs_embeds' ) def lowercase_ ( self : Optional[int] ) ->Optional[Any]: pass @unittest.skip(reason='ConvNext does not support input and output embeddings' ) def lowercase_ ( self : List[str] ) ->Union[str, Any]: pass @unittest.skip(reason='ConvNext does not use feedforward chunking' ) def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: pass def lowercase_ ( self : Union[str, Any] ) ->Optional[int]: snake_case__ , snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Optional[Any] = model_class(_snake_case ) snake_case__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : int = [*signature.parameters.keys()] snake_case__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1], _snake_case ) def lowercase_ ( self : Tuple ) ->Optional[Any]: snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def lowercase_ ( self : Dict ) ->str: snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_snake_case ) def lowercase_ ( self : Dict ) ->Any: def check_hidden_states_output(_snake_case : Optional[Any], _snake_case : int, _snake_case : Union[str, Any] ): snake_case__ : Union[str, Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Tuple = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : List[str] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case__ : Tuple = self.model_tester.num_stages self.assertEqual(len(_snake_case ), expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [self.model_tester.image_size // 4, self.model_tester.image_size // 4], ) snake_case__ , snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(_snake_case, _snake_case, _snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : Optional[Any] = True check_hidden_states_output(_snake_case, _snake_case, _snake_case ) def lowercase_ ( self : Any ) ->Any: snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def lowercase_ ( self : Tuple ) ->Tuple: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Dict = ConvNextModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def lowercase_ (): snake_case__ : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowercase_ ( self : Optional[int] ) ->Any: return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None @slow def lowercase_ ( self : Union[str, Any] ) ->Any: snake_case__ : Tuple = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(_snake_case ) snake_case__ : Optional[int] = self.default_image_processor snake_case__ : Optional[Any] = prepare_img() snake_case__ : int = image_processor(images=_snake_case, return_tensors='pt' ).to(_snake_case ) # forward pass with torch.no_grad(): snake_case__ : Union[str, Any] = model(**_snake_case ) # verify the logits snake_case__ : Tuple = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _snake_case ) snake_case__ : Dict = torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _snake_case, atol=1e-4 ) ) @require_torch class snake_case__ ( unittest.TestCase , lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = (ConvNextBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = ConvNextConfig _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Tuple ) ->Tuple: snake_case__ : List[Any] = ConvNextModelTester(self )
277
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def lowercase_ (A : str , A : List[Any] , A : Any ): # Initialise PyTorch model snake_case__ : List[Any] = LxmertConfig.from_json_file(A ) print(F'''Building PyTorch model from configuration: {config}''' ) snake_case__ : List[str] = LxmertForPreTraining(A ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(A , A , A ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , A ) if __name__ == "__main__": a_ :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a_ :Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
277
1
import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def lowercase_ (A : int ): if hor == 1_2_8: snake_case__ : Any = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') snake_case__ : Dict = (3_2, 1_2_8, 2_5_6) snake_case__ : Tuple = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 3_2: snake_case__ : Optional[int] = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') snake_case__ : int = (3_2, 6_4, 1_2_8, 2_5_6) snake_case__ : Optional[int] = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') snake_case__ : Any = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) snake_case__ : Optional[Any] = model.state_dict() snake_case__ : int = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 1_4, 'out_channels': 1_4, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_5_5_3_6, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } snake_case__ : Any = UNetaDModel(**A ) print(F'''length of state dict: {len(state_dict.keys() )}''' ) print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) snake_case__ : Tuple = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ : Any = state_dict.pop(A ) hf_value_function.load_state_dict(A ) torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , 'w' ) as f: json.dump(A , A ) def lowercase_ (): snake_case__ : Dict = { 'in_channels': 1_4, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (3_2, 6_4, 1_2_8, 2_5_6), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_5_5_3_6, 'out_channels': 1_4, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } snake_case__ : Optional[Any] = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) snake_case__ : Optional[Any] = model snake_case__ : str = UNetaDModel(**A ) print(F'''length of state dict: {len(state_dict.keys() )}''' ) print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) snake_case__ : Union[str, Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ : Optional[Any] = state_dict.pop(A ) hf_value_function.load_state_dict(A ) torch.save(hf_value_function.state_dict() , 'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' , 'w' ) as f: json.dump(A , A ) if __name__ == "__main__": unet(32) # unet(128) value_function()
277
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() a_ :Tuple = logging.get_logger(__name__) a_ :List[Any] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } a_ :Optional[int] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowercase_ (A : Union[str, Any] , A : str , A : Dict , A : Optional[Any] , A : Optional[Any] ): for attribute in key.split('.' ): snake_case__ : Any = getattr(A , A ) if weight_type is not None: snake_case__ : Optional[Any] = getattr(A , A ).shape else: snake_case__ : Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": snake_case__ : Tuple = value elif weight_type == "weight_g": snake_case__ : Tuple = value elif weight_type == "weight_v": snake_case__ : List[Any] = value elif weight_type == "bias": snake_case__ : List[Any] = value else: snake_case__ : Optional[Any] = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowercase_ (A : str , A : Any ): snake_case__ : Union[str, Any] = [] snake_case__ : Union[str, Any] = fairseq_model.state_dict() snake_case__ : Union[str, Any] = hf_model.feature_extractor snake_case__ : Any = hf_model.adapter for name, value in fairseq_dict.items(): snake_case__ : Any = False if "conv_layers" in name: load_conv_layer( A , A , A , A , hf_model.config.feat_extract_norm == 'group' , ) snake_case__ : List[Any] = True elif any(x in name for x in ['adaptor', 'w2v_encoder.proj.', 'w2v_proj_ln.'] ): load_adapter(A , A , A , A ) snake_case__ : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case__ : Tuple = True if "*" in mapped_key: snake_case__ : List[Any] = name.split(A )[0].split('.' )[-2] snake_case__ : Optional[int] = mapped_key.replace('*' , A ) if "weight_g" in name: snake_case__ : Optional[int] = 'weight_g' elif "weight_v" in name: snake_case__ : Optional[Any] = 'weight_v' elif "bias" in name: snake_case__ : Union[str, Any] = 'bias' elif "weight" in name: snake_case__ : Optional[int] = 'weight' else: snake_case__ : Tuple = None set_recursively(A , A , A , A , A ) continue if not is_used: unused_weights.append(A ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowercase_ (A : Union[str, Any] , A : Any , A : str , A : str , A : int ): snake_case__ : str = full_name.split('conv_layers.' )[-1] snake_case__ : Optional[int] = name.split('.' ) snake_case__ : Tuple = int(items[0] ) snake_case__ : Any = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) snake_case__ : Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) snake_case__ : Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) snake_case__ : Optional[int] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) snake_case__ : Optional[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(A ) def lowercase_ (A : Optional[Any] , A : Any , A : Tuple , A : Any ): snake_case__ : List[str] = full_name.split('adaptor.' )[-1] snake_case__ : Tuple = name.split('.' ) if items[1].isdigit(): snake_case__ : Optional[int] = int(items[1] ) else: snake_case__ : Any = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.''' snake_case__ : List[Any] = value logger.info(F'''Adapter proj layer norm bias was initialized from {full_name}.''' ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.''' snake_case__ : int = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.''' snake_case__ : str = value logger.info(F'''Adapter proj layer bias was initialized from {full_name}.''' ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.''' snake_case__ : Dict = value logger.info(F'''Adapter proj layer weight was initialized from {full_name}.''' ) elif isinstance(A , A ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.''' snake_case__ : List[str] = value logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.''' ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.''' snake_case__ : List[str] = value logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.''' ) else: unused_weights.append(A ) def lowercase_ (A : int ): snake_case__ , snake_case__ : Union[str, Any] = emb.weight.shape snake_case__ : int = nn.Linear(A , A , bias=A ) snake_case__ : Optional[Any] = emb.weight.data return lin_layer @torch.no_grad() def lowercase_ (A : Tuple , A : Tuple , A : Any , A : Optional[Any] , A : int , A : Optional[Any] , A : Union[str, Any] , A : Union[str, Any] , A : Optional[Any] , A : List[Any] , A : Union[str, Any] , ): snake_case__ : Optional[Any] = WavaVecaConfig.from_pretrained( A , add_adapter=A , adapter_stride=A , adapter_kernel_size=A , use_auth_token=A , output_hidden_size=A , ) snake_case__ : Dict = MBartConfig.from_pretrained(A ) # load model snake_case__ , snake_case__ , snake_case__ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={ 'config_yaml': config_yaml_path, 'data': '/'.join(dict_path.split('/' )[:-1] ), 'w2v_path': checkpoint_path, 'load_pretrained_decoder_from': None, } , ) snake_case__ : List[Any] = model[0].eval() # load feature extractor snake_case__ : str = WavaVecaFeatureExtractor.from_pretrained(A , use_auth_token=A ) # set weights for wav2vec2 encoder snake_case__ : List[str] = WavaVecaModel(A ) recursively_load_weights_wavaveca(model.encoder , A ) # load decoder weights snake_case__ : Any = MBartForCausalLM(A ) snake_case__ , snake_case__ : int = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=A ) logger.warning(F'''The following keys are missing when loading the decoder weights: {missing_keys}''' ) logger.warning(F'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' ) snake_case__ : Union[str, Any] = SpeechEncoderDecoderModel(encoder=A , decoder=A ) snake_case__ : str = False snake_case__ : int = MBartaaTokenizer(A ) tokenizer.save_pretrained(A ) snake_case__ : Any = hf_wavavec.config.to_dict() snake_case__ : Tuple = tokenizer.pad_token_id snake_case__ : Union[str, Any] = tokenizer.bos_token_id snake_case__ : Dict = tokenizer.eos_token_id snake_case__ : Optional[int] = 'mbart50' snake_case__ : Union[str, Any] = 'wav2vec2' snake_case__ : List[str] = tokenizer.eos_token_id snake_case__ : Union[str, Any] = 2_5_0_0_0_4 snake_case__ : int = tokenizer.eos_token_id snake_case__ : Union[str, Any] = SpeechEncoderDecoderConfig.from_dict(A ) hf_wavavec.save_pretrained(A ) feature_extractor.save_pretrained(A ) if __name__ == "__main__": a_ :str = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-xls-r-1b", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/mbart-large-50-one-to-many-mmt", type=str, help="Path to hf decoder checkpoint config", ) parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers") parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers") parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers") parser.add_argument("--encoder_output_dim", default=1_024, type=int, help="encoder output dim") parser.add_argument("--start_token_id", default=250_004, type=int, help="`decoder_start_token_id` of model config") a_ :Union[str, Any] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
277
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 ): """simple docstring""" _SCREAMING_SNAKE_CASE = KandinskyInpaintPipeline _SCREAMING_SNAKE_CASE = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image"""] _SCREAMING_SNAKE_CASE = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image""", ] _SCREAMING_SNAKE_CASE = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _SCREAMING_SNAKE_CASE = False @property def lowercase_ ( self : Optional[int] ) ->Optional[Any]: return 3_2 @property def lowercase_ ( self : Dict ) ->Tuple: return 3_2 @property def lowercase_ ( self : List[str] ) ->int: return self.time_input_dim @property def lowercase_ ( self : List[str] ) ->Optional[int]: return self.time_input_dim * 4 @property def lowercase_ ( self : str ) ->List[Any]: return 1_0_0 @property def lowercase_ ( self : Union[str, Any] ) ->Tuple: snake_case__ : List[Any] = XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def lowercase_ ( self : List[Any] ) ->str: torch.manual_seed(0 ) snake_case__ : Tuple = MCLIPConfig( numDims=self.cross_attention_dim, transformerDimensions=self.text_embedder_hidden_size, hidden_size=self.text_embedder_hidden_size, intermediate_size=3_7, num_attention_heads=4, num_hidden_layers=5, vocab_size=1_0_0_5, ) snake_case__ : Dict = MultilingualCLIP(_snake_case ) snake_case__ : Any = text_encoder.eval() return text_encoder @property def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: torch.manual_seed(0 ) snake_case__ : Union[str, Any] = { 'in_channels': 9, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'text_image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'text_image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } snake_case__ : Optional[int] = UNetaDConditionModel(**_snake_case ) return model @property def lowercase_ ( self : Any ) ->Tuple: return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowercase_ ( self : str ) ->Dict: torch.manual_seed(0 ) snake_case__ : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def lowercase_ ( self : str ) ->List[Any]: snake_case__ : str = self.dummy_text_encoder snake_case__ : Optional[Any] = self.dummy_tokenizer snake_case__ : List[Any] = self.dummy_unet snake_case__ : Optional[int] = self.dummy_movq snake_case__ : Optional[Any] = DDIMScheduler( num_train_timesteps=1_0_0_0, beta_schedule='linear', beta_start=0.0_0_0_8_5, beta_end=0.0_1_2, clip_sample=_snake_case, set_alpha_to_one=_snake_case, steps_offset=1, prediction_type='epsilon', thresholding=_snake_case, ) snake_case__ : Union[str, Any] = { 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowercase_ ( self : str, _snake_case : Any, _snake_case : Tuple=0 ) ->str: snake_case__ : List[str] = floats_tensor((1, self.cross_attention_dim), rng=random.Random(_snake_case ) ).to(_snake_case ) snake_case__ : List[str] = floats_tensor((1, self.cross_attention_dim), rng=random.Random(seed + 1 ) ).to(_snake_case ) # create init_image snake_case__ : Any = floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(_snake_case ) ).to(_snake_case ) snake_case__ : int = image.cpu().permute(0, 2, 3, 1 )[0] snake_case__ : Dict = Image.fromarray(np.uinta(_snake_case ) ).convert('RGB' ).resize((2_5_6, 2_5_6) ) # create mask snake_case__ : Optional[Any] = np.ones((6_4, 6_4), dtype=np.floataa ) snake_case__ : Optional[Any] = 0 if str(_snake_case ).startswith('mps' ): snake_case__ : Any = torch.manual_seed(_snake_case ) else: snake_case__ : int = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) snake_case__ : int = { 'prompt': 'horse', 'image': init_image, 'mask_image': mask, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 6_4, 'width': 6_4, 'num_inference_steps': 2, 'guidance_scale': 4.0, 'output_type': 'np', } return inputs def lowercase_ ( self : List[str] ) ->Any: snake_case__ : Any = 'cpu' snake_case__ : str = self.get_dummy_components() snake_case__ : Any = self.pipeline_class(**_snake_case ) snake_case__ : Any = pipe.to(_snake_case ) pipe.set_progress_bar_config(disable=_snake_case ) snake_case__ : Optional[int] = pipe(**self.get_dummy_inputs(_snake_case ) ) snake_case__ : int = output.images snake_case__ : str = pipe( **self.get_dummy_inputs(_snake_case ), return_dict=_snake_case, )[0] snake_case__ : Optional[Any] = image[0, -3:, -3:, -1] snake_case__ : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] print(F'''image.shape {image.shape}''' ) assert image.shape == (1, 6_4, 6_4, 3) snake_case__ : Any = np.array( [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6] ) 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()}''' def lowercase_ ( self : Dict ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self : int ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Any ) ->Tuple: snake_case__ : Optional[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy' ) snake_case__ : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) snake_case__ : Dict = np.ones((7_6_8, 7_6_8), dtype=np.floataa ) snake_case__ : Union[str, Any] = 0 snake_case__ : Optional[Any] = 'a hat' snake_case__ : Optional[int] = KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior', torch_dtype=torch.floataa ) pipe_prior.to(_snake_case ) snake_case__ : List[str] = KandinskyInpaintPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-inpaint', torch_dtype=torch.floataa ) snake_case__ : Any = pipeline.to(_snake_case ) pipeline.set_progress_bar_config(disable=_snake_case ) snake_case__ : Dict = torch.Generator(device='cpu' ).manual_seed(0 ) snake_case__ , snake_case__ : List[Any] = pipe_prior( _snake_case, generator=_snake_case, num_inference_steps=5, negative_prompt='', ).to_tuple() snake_case__ : Dict = pipeline( _snake_case, image=_snake_case, mask_image=_snake_case, image_embeds=_snake_case, negative_image_embeds=_snake_case, generator=_snake_case, num_inference_steps=1_0_0, height=7_6_8, width=7_6_8, output_type='np', ) snake_case__ : List[Any] = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_snake_case, _snake_case )
277
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType a_ :Tuple = logging.get_logger(__name__) a_ :Union[str, Any] = { "microsoft/deberta-v2-xlarge": "https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json", "microsoft/deberta-v2-xxlarge": "https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json", "microsoft/deberta-v2-xlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json" ), "microsoft/deberta-v2-xxlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json" ), } class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """deberta-v2""" def __init__( self : Union[str, Any], _snake_case : Dict=1_2_8_1_0_0, _snake_case : Any=1_5_3_6, _snake_case : Tuple=2_4, _snake_case : int=2_4, _snake_case : Optional[int]=6_1_4_4, _snake_case : Optional[int]="gelu", _snake_case : Optional[int]=0.1, _snake_case : List[str]=0.1, _snake_case : str=5_1_2, _snake_case : Optional[int]=0, _snake_case : Optional[int]=0.0_2, _snake_case : Dict=1e-7, _snake_case : int=False, _snake_case : Any=-1, _snake_case : List[str]=0, _snake_case : Tuple=True, _snake_case : Any=None, _snake_case : Union[str, Any]=0, _snake_case : Tuple="gelu", **_snake_case : Union[str, Any], ) ->Optional[int]: super().__init__(**_snake_case ) snake_case__ : Dict = hidden_size snake_case__ : Optional[int] = num_hidden_layers snake_case__ : Any = num_attention_heads snake_case__ : List[Any] = intermediate_size snake_case__ : List[Any] = hidden_act snake_case__ : Union[str, Any] = hidden_dropout_prob snake_case__ : Dict = attention_probs_dropout_prob snake_case__ : List[str] = max_position_embeddings snake_case__ : List[str] = type_vocab_size snake_case__ : Optional[Any] = initializer_range snake_case__ : Optional[int] = relative_attention snake_case__ : Tuple = max_relative_positions snake_case__ : Union[str, Any] = pad_token_id snake_case__ : Optional[int] = position_biased_input # Backwards compatibility if type(_snake_case ) == str: snake_case__ : int = [x.strip() for x in pos_att_type.lower().split('|' )] snake_case__ : List[str] = pos_att_type snake_case__ : Union[str, Any] = vocab_size snake_case__ : Optional[int] = layer_norm_eps snake_case__ : Optional[int] = kwargs.get('pooler_hidden_size', _snake_case ) snake_case__ : int = pooler_dropout snake_case__ : str = pooler_hidden_act class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" @property def lowercase_ ( self : Optional[int] ) ->Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case__ : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case__ : int = {0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def lowercase_ ( self : Dict ) ->int: return 1_2 def lowercase_ ( self : Tuple, _snake_case : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], _snake_case : int = -1, _snake_case : int = -1, _snake_case : int = -1, _snake_case : bool = False, _snake_case : Optional["TensorType"] = None, _snake_case : int = 3, _snake_case : int = 4_0, _snake_case : int = 4_0, _snake_case : "PreTrainedTokenizerBase" = None, ) ->Mapping[str, Any]: snake_case__ : Union[str, Any] = super().generate_dummy_inputs(preprocessor=_snake_case, framework=_snake_case ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
277
1
from __future__ import annotations from math import ceil, floor, sqrt def lowercase_ (A : int = 2_0_0_0_0_0_0 ): snake_case__ : list[int] = [0] snake_case__ : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target snake_case__ : int = 0 # the area corresponding to the grid that gives the product closest to target snake_case__ : int = 0 # an estimate of b, using the quadratic formula snake_case__ : float # the largest integer less than b_estimate snake_case__ : int # the largest integer less than b_estimate snake_case__ : int # the triangle number corresponding to b_floor snake_case__ : int # the triangle number corresponding to b_ceil snake_case__ : int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): snake_case__ : Dict = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 snake_case__ : Optional[Any] = floor(A ) snake_case__ : List[Any] = ceil(A ) snake_case__ : Union[str, Any] = triangle_numbers[b_floor] snake_case__ : Any = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): snake_case__ : List[str] = triangle_b_first_guess * triangle_a snake_case__ : Dict = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): snake_case__ : int = triangle_b_second_guess * triangle_a snake_case__ : List[Any] = idx_a * b_ceil return area if __name__ == "__main__": print(F"""{solution() = }""")
277
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a_ :str = logging.get_logger(__name__) def lowercase_ (A : str ): snake_case__ : Tuple = SwinConfig.from_pretrained( 'microsoft/swin-tiny-patch4-window7-224' , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) snake_case__ : List[Any] = MaskFormerConfig(backbone_config=A ) snake_case__ : Union[str, Any] = 'huggingface/label-files' if "ade20k-full" in model_name: # this should be ok snake_case__ : Dict = 8_4_7 snake_case__ : List[str] = 'maskformer-ade20k-full-id2label.json' elif "ade" in model_name: # this should be ok snake_case__ : Union[str, Any] = 1_5_0 snake_case__ : Any = 'ade20k-id2label.json' elif "coco-stuff" in model_name: # this should be ok snake_case__ : List[str] = 1_7_1 snake_case__ : Union[str, Any] = 'maskformer-coco-stuff-id2label.json' elif "coco" in model_name: # TODO snake_case__ : Dict = 1_3_3 snake_case__ : str = 'coco-panoptic-id2label.json' elif "cityscapes" in model_name: # this should be ok snake_case__ : List[str] = 1_9 snake_case__ : Union[str, Any] = 'cityscapes-id2label.json' elif "vistas" in model_name: # this should be ok snake_case__ : Tuple = 6_5 snake_case__ : List[str] = 'mapillary-vistas-id2label.json' snake_case__ : Dict = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) ) snake_case__ : List[str] = {int(A ): v for k, v in idalabel.items()} return config def lowercase_ (A : Any ): snake_case__ : Optional[int] = [] # stem # fmt: off rename_keys.append(('backbone.patch_embed.proj.weight', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.proj.bias', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'model.pixel_level_module.encoder.model.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'model.pixel_level_module.encoder.model.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.layers.{i}.downsample.reduction.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(('sem_seg_head.layer_4.weight', 'model.pixel_level_module.decoder.fpn.stem.0.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.weight', 'model.pixel_level_module.decoder.fpn.stem.1.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.bias', 'model.pixel_level_module.decoder.fpn.stem.1.bias') ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((F'''sem_seg_head.adapter_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(('sem_seg_head.mask_features.weight', 'model.pixel_level_module.decoder.mask_projection.weight') ) rename_keys.append(('sem_seg_head.mask_features.bias', 'model.pixel_level_module.decoder.mask_projection.bias') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.weight', 'model.transformer_module.decoder.layernorm.weight') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.bias', 'model.transformer_module.decoder.layernorm.bias') ) # heads on top rename_keys.append(('sem_seg_head.predictor.query_embed.weight', 'model.transformer_module.queries_embedder.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.weight', 'model.transformer_module.input_projection.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.bias', 'model.transformer_module.input_projection.bias') ) rename_keys.append(('sem_seg_head.predictor.class_embed.weight', 'class_predictor.weight') ) rename_keys.append(('sem_seg_head.predictor.class_embed.bias', 'class_predictor.bias') ) for i in range(3 ): rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', F'''mask_embedder.{i}.0.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', F'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def lowercase_ (A : Tuple , A : Tuple , A : Optional[Any] ): snake_case__ : Optional[int] = dct.pop(A ) snake_case__ : Union[str, Any] = val def lowercase_ (A : Optional[Any] , A : Tuple ): snake_case__ : Optional[int] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): snake_case__ : Optional[int] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) snake_case__ : int = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) snake_case__ : Tuple = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : str = in_proj_weight[:dim, :] snake_case__ : int = in_proj_bias[: dim] snake_case__ : List[Any] = in_proj_weight[ dim : dim * 2, : ] snake_case__ : List[str] = in_proj_bias[ dim : dim * 2 ] snake_case__ : List[Any] = in_proj_weight[ -dim :, : ] snake_case__ : Dict = in_proj_bias[-dim :] # fmt: on def lowercase_ (A : List[str] , A : List[Any] ): # fmt: off snake_case__ : str = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) snake_case__ : int = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Any = in_proj_weight[: hidden_size, :] snake_case__ : Tuple = in_proj_bias[:config.hidden_size] snake_case__ : List[str] = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : Dict = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : Any = in_proj_weight[-hidden_size :, :] snake_case__ : int = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) snake_case__ : List[str] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[: hidden_size, :] snake_case__ : Optional[Any] = in_proj_bias[:config.hidden_size] snake_case__ : int = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case__ : List[str] = in_proj_bias[hidden_size : hidden_size * 2] snake_case__ : List[str] = in_proj_weight[-hidden_size :, :] snake_case__ : str = in_proj_bias[-hidden_size :] # fmt: on def lowercase_ (): snake_case__ : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : int = Image.open(requests.get(A , stream=A ).raw ) return im @torch.no_grad() def lowercase_ (A : str , A : str , A : str , A : bool = False ): snake_case__ : Optional[int] = get_maskformer_config(A ) # load original state_dict with open(A , 'rb' ) as f: snake_case__ : List[Any] = pickle.load(A ) snake_case__ : Optional[int] = data['model'] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys snake_case__ : List[str] = create_rename_keys(A ) for src, dest in rename_keys: rename_key(A , A , A ) read_in_swin_q_k_v(A , config.backbone_config ) read_in_decoder_q_k_v(A , A ) # update to torch tensors for key, value in state_dict.items(): snake_case__ : int = torch.from_numpy(A ) # load 🤗 model snake_case__ : str = MaskFormerForInstanceSegmentation(A ) model.eval() for name, param in model.named_parameters(): print(A , param.shape ) snake_case__ , snake_case__ : Union[str, Any] = model.load_state_dict(A , strict=A ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(A ) == 0, F'''Unexpected keys: {unexpected_keys}''' # verify results snake_case__ : Optional[Any] = prepare_img() if "vistas" in model_name: snake_case__ : int = 6_5 elif "cityscapes" in model_name: snake_case__ : Dict = 6_5_5_3_5 else: snake_case__ : Tuple = 2_5_5 snake_case__ : Optional[int] = True if 'ade' in model_name else False snake_case__ : Dict = MaskFormerImageProcessor(ignore_index=A , reduce_labels=A ) snake_case__ : Any = image_processor(A , return_tensors='pt' ) snake_case__ : Any = model(**A ) print('Logits:' , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": snake_case__ : Tuple = torch.tensor( [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , A , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(A ).mkdir(exist_ok=A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) if push_to_hub: print('Pushing model and image processor to the hub...' ) model.push_to_hub(F'''nielsr/{model_name}''' ) image_processor.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a_ :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="maskformer-swin-tiny-ade", type=str, help=("Name of the MaskFormer model you'd like to convert",), ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl", type=str, help="Path to the original state dict (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a_ :Dict = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
277
1