code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder SCREAMING_SNAKE_CASE__ : Optional[int] = """base_with_context""" def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Optional[int] = nn.Parameter(torch.FloatTensor(weights['''token_embedder''']['''embedding'''] ) ) __magic_name__ :Dict = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ), requires_grad=snake_case ) for lyr_num, lyr in enumerate(model.encoders ): __magic_name__ :Optional[int] = weights[f'''layers_{lyr_num}'''] __magic_name__ :Dict = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __magic_name__ :Tuple = ly_weight['''attention'''] __magic_name__ :Any = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __magic_name__ :Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __magic_name__ :List[str] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __magic_name__ :Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __magic_name__ :List[str] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __magic_name__ :Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __magic_name__ :List[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __magic_name__ :Tuple = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Dict = nn.Parameter(torch.FloatTensor(weights['''input_proj''']['''kernel'''].T ) ) __magic_name__ :Union[str, Any] = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ), requires_grad=snake_case ) for lyr_num, lyr in enumerate(model.encoders ): __magic_name__ :Union[str, Any] = weights[f'''layers_{lyr_num}'''] __magic_name__ :Any = ly_weight['''attention'''] __magic_name__ :Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __magic_name__ :List[str] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __magic_name__ :Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __magic_name__ :Dict = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __magic_name__ :Optional[Any] = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __magic_name__ :Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __magic_name__ :List[str] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __magic_name__ :Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Dict = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense0''']['''kernel'''].T ) ) __magic_name__ :str = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense1''']['''kernel'''].T ) ) __magic_name__ :List[str] = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ), requires_grad=snake_case ) __magic_name__ :Optional[Any] = nn.Parameter( torch.FloatTensor(weights['''continuous_inputs_projection''']['''kernel'''].T ) ) for lyr_num, lyr in enumerate(model.decoders ): __magic_name__ :Optional[int] = weights[f'''layers_{lyr_num}'''] __magic_name__ :Optional[int] = nn.Parameter( torch.FloatTensor(ly_weight['''pre_self_attention_layer_norm''']['''scale'''] ) ) __magic_name__ :Optional[Any] = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_0''']['''DenseGeneral_0''']['''kernel'''].T ) ) __magic_name__ :Tuple = ly_weight['''self_attention'''] __magic_name__ :Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __magic_name__ :str = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __magic_name__ :Any = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __magic_name__ :int = ly_weight['''MultiHeadDotProductAttention_0'''] __magic_name__ :Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __magic_name__ :Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __magic_name__ :Any = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __magic_name__ :str = nn.Parameter( torch.FloatTensor(ly_weight['''pre_cross_attention_layer_norm''']['''scale'''] ) ) __magic_name__ :Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __magic_name__ :Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_1''']['''DenseGeneral_0''']['''kernel'''].T ) ) __magic_name__ :Any = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __magic_name__ :Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __magic_name__ :List[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __magic_name__ :Union[str, Any] = nn.Parameter(torch.FloatTensor(weights['''decoder_norm''']['''scale'''] ) ) __magic_name__ :int = nn.Parameter(torch.FloatTensor(weights['''spec_out_dense''']['''kernel'''].T ) ) return model def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Union[str, Any] = checkpoints.load_tax_checkpoint(args.checkpoint_path ) __magic_name__ :Tuple = jnp.tree_util.tree_map(onp.array, snake_case ) __magic_name__ :Optional[int] = [ '''from __gin__ import dynamic_registration''', '''from music_spectrogram_diffusion.models.diffusion import diffusion_utils''', '''diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0''', '''diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()''', ] __magic_name__ :Dict = os.path.join(args.checkpoint_path, '''..''', '''config.gin''' ) __magic_name__ :Dict = inference.parse_training_gin_file(snake_case, snake_case ) __magic_name__ :Optional[int] = inference.InferenceModel(args.checkpoint_path, snake_case ) __magic_name__ :List[str] = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''', variance_type='''fixed_large''' ) __magic_name__ :List[str] = SpectrogramNotesEncoder( max_length=synth_model.sequence_length['''inputs'''], vocab_size=synth_model.model.module.config.vocab_size, d_model=synth_model.model.module.config.emb_dim, dropout_rate=synth_model.model.module.config.dropout_rate, num_layers=synth_model.model.module.config.num_encoder_layers, num_heads=synth_model.model.module.config.num_heads, d_kv=synth_model.model.module.config.head_dim, d_ff=synth_model.model.module.config.mlp_dim, feed_forward_proj='''gated-gelu''', ) __magic_name__ :str = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims, targets_context_length=synth_model.sequence_length['''targets_context'''], d_model=synth_model.model.module.config.emb_dim, dropout_rate=synth_model.model.module.config.dropout_rate, num_layers=synth_model.model.module.config.num_encoder_layers, num_heads=synth_model.model.module.config.num_heads, d_kv=synth_model.model.module.config.head_dim, d_ff=synth_model.model.module.config.mlp_dim, feed_forward_proj='''gated-gelu''', ) __magic_name__ :Dict = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims, targets_length=synth_model.sequence_length['''targets_context'''], max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time, d_model=synth_model.model.module.config.emb_dim, num_layers=synth_model.model.module.config.num_decoder_layers, num_heads=synth_model.model.module.config.num_heads, d_kv=synth_model.model.module.config.head_dim, d_ff=synth_model.model.module.config.mlp_dim, dropout_rate=synth_model.model.module.config.dropout_rate, ) __magic_name__ :int = load_notes_encoder(ta_checkpoint['''target''']['''token_encoder'''], snake_case ) __magic_name__ :Any = load_continuous_encoder(ta_checkpoint['''target''']['''continuous_encoder'''], snake_case ) __magic_name__ :int = load_decoder(ta_checkpoint['''target''']['''decoder'''], snake_case ) __magic_name__ :int = OnnxRuntimeModel.from_pretrained('''kashif/soundstream_mel_decoder''' ) __magic_name__ :List[Any] = SpectrogramDiffusionPipeline( notes_encoder=snake_case, continuous_encoder=snake_case, decoder=snake_case, scheduler=snake_case, melgan=snake_case, ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--output_path""", default=None, type=str, required=True, help="""Path to the converted model.""") parser.add_argument( """--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not.""" ) parser.add_argument( """--checkpoint_path""", default=f"{MODEL}/checkpoint_500000", type=str, required=False, help="""Path to the original jax model checkpoint.""", ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() main(args)
0
import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def __lowercase ( snake_case = N ): """simple docstring""" __magic_name__ :Optional[int] = -sys.maxsize - 1 for i in range(len(snake_case ) - 1_2 ): __magic_name__ :List[Any] = 1 for j in range(1_3 ): product *= int(n[i + j] ) if product > largest_product: __magic_name__ :str = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
0
1
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 lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase=1_3 , __lowerCAmelCase=7 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=9_9 , __lowerCAmelCase=3_2 , __lowerCAmelCase=2 , __lowerCAmelCase=4 , __lowerCAmelCase=3_7 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=5_1_2 , __lowerCAmelCase=1_6 , __lowerCAmelCase=2 , __lowerCAmelCase=0.02 , __lowerCAmelCase=3 , __lowerCAmelCase=4 , __lowerCAmelCase=None , ): """simple docstring""" __magic_name__ :Optional[int] = parent __magic_name__ :List[Any] = 1_3 __magic_name__ :Union[str, Any] = 7 __magic_name__ :Optional[Any] = True __magic_name__ :Tuple = True __magic_name__ :List[str] = True __magic_name__ :List[Any] = True __magic_name__ :int = 9_9 __magic_name__ :Any = 3_2 __magic_name__ :Union[str, Any] = 2 __magic_name__ :List[str] = 4 __magic_name__ :List[Any] = 3_7 __magic_name__ :Tuple = '''gelu''' __magic_name__ :Any = 0.1 __magic_name__ :str = 0.1 __magic_name__ :List[str] = 5_1_2 __magic_name__ :int = 1_6 __magic_name__ :Any = 2 __magic_name__ :List[Any] = 0.02 __magic_name__ :Optional[Any] = 3 __magic_name__ :Tuple = 4 __magic_name__ :Optional[Any] = None def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ :str = None if self.use_input_mask: __magic_name__ :Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ :str = None if self.use_token_type_ids: __magic_name__ :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ :Union[str, Any] = None __magic_name__ :Tuple = None __magic_name__ :str = None if self.use_labels: __magic_name__ :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ :List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ :str = 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=__lowerCAmelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :int = TFRoFormerModel(config=__lowerCAmelCase ) __magic_name__ :Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __magic_name__ :List[str] = [input_ids, input_mask] __magic_name__ :Any = model(__lowerCAmelCase ) __magic_name__ :List[str] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Dict = True __magic_name__ :List[str] = TFRoFormerForCausalLM(config=__lowerCAmelCase ) __magic_name__ :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Optional[Any] = model(__lowerCAmelCase )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = TFRoFormerForMaskedLM(config=__lowerCAmelCase ) __magic_name__ :Any = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :int = self.num_labels __magic_name__ :str = TFRoFormerForSequenceClassification(config=__lowerCAmelCase ) __magic_name__ :Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :str = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Union[str, Any] = self.num_choices __magic_name__ :Tuple = TFRoFormerForMultipleChoice(config=__lowerCAmelCase ) __magic_name__ :int = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :Optional[Any] = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :Union[str, Any] = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :str = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __magic_name__ :Tuple = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[int] = self.num_labels __magic_name__ :Any = TFRoFormerForTokenClassification(config=__lowerCAmelCase ) __magic_name__ :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :List[str] = TFRoFormerForQuestionAnswering(config=__lowerCAmelCase ) __magic_name__ :List[str] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Union[str, Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) :Union[str, Any] = config_and_inputs __magic_name__ :Optional[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCamelCase_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): a__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) a__ = ( { '''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 {} ) a__ = False a__ = False def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def A ( self ): """simple docstring""" __magic_name__ :List[str] = TFRoFormerModelTester(self ) __magic_name__ :List[str] = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def A ( self ): """simple docstring""" self.config_tester.run_common_tests() def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase ) @slow def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(__lowerCAmelCase ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): @slow def A ( self ): """simple docstring""" __magic_name__ :int = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __magic_name__ :Dict = tf.constant([[0, 1, 2, 3, 4, 5]] ) __magic_name__ :Optional[Any] = model(__lowerCAmelCase )[0] # TODO Replace vocab size __magic_name__ :int = 5_0_0_0_0 __magic_name__ :Tuple = [1, 6, vocab_size] self.assertEqual(output.shape , __lowerCAmelCase ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. __magic_name__ :Any = 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] , __lowerCAmelCase , atol=1E-4 ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): a__ = 1e-4 def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = tf.constant([[4, 1_0]] ) __magic_name__ :Optional[int] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) __magic_name__ :Optional[Any] = emba(input_ids.shape ) __magic_name__ :List[str] = 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(__lowerCAmelCase , __lowerCAmelCase , atol=self.tolerance ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = 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], ] ) __magic_name__ :Union[str, Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) __magic_name__ :Optional[int] = emba.weight[:3, :5] tf.debugging.assert_near(__lowerCAmelCase , __lowerCAmelCase , atol=self.tolerance ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): a__ = 1e-4 def A ( self ): """simple docstring""" # 2,12,16,64 __magic_name__ :int = tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __magic_name__ :str = -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __magic_name__ :int = TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) __magic_name__ :List[str] = embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] __magic_name__ , __magic_name__ :Union[str, Any] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :Tuple = 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], ] ) __magic_name__ :List[str] = 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] , __lowerCAmelCase , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , __lowerCAmelCase , atol=self.tolerance )
0
SCREAMING_SNAKE_CASE__ : Tuple = { """a""": """AAAAA""", """b""": """AAAAB""", """c""": """AAABA""", """d""": """AAABB""", """e""": """AABAA""", """f""": """AABAB""", """g""": """AABBA""", """h""": """AABBB""", """i""": """ABAAA""", """j""": """BBBAA""", """k""": """ABAAB""", """l""": """ABABA""", """m""": """ABABB""", """n""": """ABBAA""", """o""": """ABBAB""", """p""": """ABBBA""", """q""": """ABBBB""", """r""": """BAAAA""", """s""": """BAAAB""", """t""": """BAABA""", """u""": """BAABB""", """v""": """BBBAB""", """w""": """BABAA""", """x""": """BABAB""", """y""": """BABBA""", """z""": """BABBB""", """ """: """ """, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = {value: key for key, value in encode_dict.items()} def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Tuple = '''''' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('''encode() accepts only letters of the alphabet and spaces''' ) return encoded def __lowercase ( snake_case ): """simple docstring""" if set(snake_case ) - {"A", "B", " "} != set(): raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' ) __magic_name__ :Dict = '''''' for word in coded.split(): while len(snake_case ) != 0: decoded += decode_dict[word[:5]] __magic_name__ :int = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
0
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase_ ( lowerCamelCase ): a__ = ['''image_processor''', '''tokenizer'''] a__ = '''CLIPImageProcessor''' a__ = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase ): """simple docstring""" __magic_name__ :Dict = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __lowerCAmelCase , ) __magic_name__ :Union[str, Any] = kwargs.pop('''feature_extractor''' ) __magic_name__ :List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(__lowerCAmelCase , __lowerCAmelCase ) def __call__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: __magic_name__ :int = self.tokenizer(__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase ) if images is not None: __magic_name__ :Optional[Any] = self.image_processor(__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None and images is not None: __magic_name__ :Dict = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__lowerCAmelCase ) , tensor_type=__lowerCAmelCase ) def A ( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def A ( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @property def A ( self ): """simple docstring""" __magic_name__ :List[Any] = self.tokenizer.model_input_names __magic_name__ :Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
0
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Optional[Any] = [ '''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(snake_case, snake_case ) def __lowercase ( snake_case ): """simple docstring""" __magic_name__ , __magic_name__ :Tuple = emb.weight.shape __magic_name__ :int = nn.Linear(snake_case, snake_case, bias=snake_case ) __magic_name__ :str = emb.weight.data return lin_layer def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :int = torch.load(snake_case, map_location='''cpu''' ) __magic_name__ :Optional[Any] = mam_aaa['''args'''] or mam_aaa['''cfg''']['''model'''] __magic_name__ :List[Any] = mam_aaa['''model'''] remove_ignore_keys_(snake_case ) __magic_name__ :Tuple = state_dict['''encoder.embed_tokens.weight'''].shape[0] __magic_name__ :List[str] = MaMaaaConfig( vocab_size=snake_case, max_position_embeddings=1_0_2_4, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, encoder_attention_heads=args.encoder_attention_heads, decoder_attention_heads=args.decoder_attention_heads, encoder_ffn_dim=args.encoder_ffn_embed_dim, decoder_ffn_dim=args.decoder_ffn_embed_dim, d_model=args.encoder_embed_dim, encoder_layerdrop=args.encoder_layerdrop, decoder_layerdrop=args.decoder_layerdrop, dropout=args.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_function='''relu''', ) __magic_name__ :int = state_dict['''decoder.embed_tokens.weight'''] __magic_name__ :List[str] = MaMaaaForConditionalGeneration(snake_case ) model.model.load_state_dict(snake_case, strict=snake_case ) __magic_name__ :List[str] = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("""fairseq_path""", type=str, help="""path to a model.pt on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") SCREAMING_SNAKE_CASE__ : int = parser.parse_args() SCREAMING_SNAKE_CASE__ : Any = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
0
1
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class lowerCamelCase_ : a__ = None a__ = False a__ = False a__ = False a__ = None a__ = None a__ = False a__ = False a__ = False a__ = True a__ = None a__ = 1 a__ = None a__ = False a__ = None a__ = None def A ( self ): """simple docstring""" return self.__class__(**{k: copy.deepcopy(__lowerCAmelCase ) for k, v in self.__dict__.items()} )
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : Dict = { """configuration_canine""": ["""CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CanineConfig"""], """tokenization_canine""": ["""CanineTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ """CANINE_PRETRAINED_MODEL_ARCHIVE_LIST""", """CanineForMultipleChoice""", """CanineForQuestionAnswering""", """CanineForSequenceClassification""", """CanineForTokenClassification""", """CanineLayer""", """CanineModel""", """CaninePreTrainedModel""", """load_tf_weights_in_canine""", ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
0
1
import os # Precomputes a list of the 100 first triangular numbers SCREAMING_SNAKE_CASE__ : List[str] = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def __lowercase ( ): """simple docstring""" __magic_name__ :List[Any] = os.path.dirname(os.path.realpath(snake_case ) ) __magic_name__ :str = os.path.join(snake_case, '''words.txt''' ) __magic_name__ :Any = '''''' with open(snake_case ) as f: __magic_name__ :List[Any] = f.readline() __magic_name__ :List[str] = [word.strip('''"''' ) for word in words.strip('''\r\n''' ).split(''',''' )] __magic_name__ :List[str] = [ word for word in [sum(ord(snake_case ) - 6_4 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(snake_case ) if __name__ == "__main__": print(solution())
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase_ ( lowerCamelCase ): a__ = ['''image_processor''', '''tokenizer'''] a__ = '''ChineseCLIPImageProcessor''' a__ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase ): """simple docstring""" __magic_name__ :Tuple = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __lowerCAmelCase , ) __magic_name__ :Optional[Any] = kwargs.pop('''feature_extractor''' ) __magic_name__ :Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :List[Any] = self.image_processor def __call__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: __magic_name__ :int = self.tokenizer(__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase ) if images is not None: __magic_name__ :Dict = self.image_processor(__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None and images is not None: __magic_name__ :Union[str, Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__lowerCAmelCase ) , tensor_type=__lowerCAmelCase ) def A ( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def A ( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @property def A ( self ): """simple docstring""" __magic_name__ :List[Any] = self.tokenizer.model_input_names __magic_name__ :Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def A ( self ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __lowerCAmelCase , ) return self.image_processor_class
0
1
import itertools import math def __lowercase ( snake_case ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(snake_case ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowercase ( ): """simple docstring""" __magic_name__ :str = 2 while True: if is_prime(snake_case ): yield num num += 1 def __lowercase ( snake_case = 1_0_0_0_1 ): """simple docstring""" return next(itertools.islice(prime_generator(), nth - 1, snake_case ) ) if __name__ == "__main__": print(f"{solution() = }")
0
from sklearn.metrics import matthews_corrcoef import datasets SCREAMING_SNAKE_CASE__ : Optional[Any] = """ Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] """ SCREAMING_SNAKE_CASE__ : Union[str, Any] = """ Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results['matthews_correlation'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results['matthews_correlation'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results['matthews_correlation'], 2)) -0.25 """ SCREAMING_SNAKE_CASE__ : int = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): def A ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None ): """simple docstring""" return { "matthews_correlation": float(matthews_corrcoef(__lowerCAmelCase , __lowerCAmelCase , sample_weight=__lowerCAmelCase ) ), }
0
1
import re from filelock import FileLock try: import nltk SCREAMING_SNAKE_CASE__ : Tuple = True except (ImportError, ModuleNotFoundError): SCREAMING_SNAKE_CASE__ : Union[str, Any] = False if NLTK_AVAILABLE: with FileLock(""".lock""") as lock: nltk.download("""punkt""", quiet=True) def __lowercase ( snake_case ): """simple docstring""" re.sub('''<n>''', '''''', snake_case ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(snake_case ) )
0
from __future__ import annotations def __lowercase ( snake_case, snake_case ): """simple docstring""" print(f'''Vertex\tShortest Distance from vertex {src}''' ) for i, d in enumerate(snake_case ): print(f'''{i}\t\t{d}''' ) def __lowercase ( snake_case, snake_case, snake_case ): """simple docstring""" for j in range(snake_case ): __magic_name__ , __magic_name__ , __magic_name__ :Tuple = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: return True return False def __lowercase ( snake_case, snake_case, snake_case, snake_case ): """simple docstring""" __magic_name__ :List[Any] = [float('''inf''' )] * vertex_count __magic_name__ :Tuple = 0.0 for _ in range(vertex_count - 1 ): for j in range(snake_case ): __magic_name__ , __magic_name__ , __magic_name__ :Dict = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: __magic_name__ :Tuple = distance[u] + w __magic_name__ :Tuple = check_negative_cycle(snake_case, snake_case, snake_case ) if negative_cycle_exists: raise Exception('''Negative cycle found''' ) return distance if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ : Tuple = int(input("""Enter number of vertices: """).strip()) SCREAMING_SNAKE_CASE__ : Any = int(input("""Enter number of edges: """).strip()) SCREAMING_SNAKE_CASE__ : list[dict[str, int]] = [{} for _ in range(E)] for i in range(E): print("""Edge """, i + 1) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = ( int(x) for x in input("""Enter source, destination, weight: """).strip().split(""" """) ) SCREAMING_SNAKE_CASE__ : Dict = {"""src""": src, """dst""": dest, """weight""": weight} SCREAMING_SNAKE_CASE__ : List[Any] = int(input("""\nEnter shortest path source:""").strip()) SCREAMING_SNAKE_CASE__ : List[str] = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
0
1
import numpy as np def __lowercase ( snake_case ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def __lowercase ( snake_case ): """simple docstring""" return vector * sigmoid(snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
0
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 lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase=1_3 , __lowerCAmelCase=7 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=9_9 , __lowerCAmelCase=3_2 , __lowerCAmelCase=2 , __lowerCAmelCase=4 , __lowerCAmelCase=3_7 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=5_1_2 , __lowerCAmelCase=1_6 , __lowerCAmelCase=2 , __lowerCAmelCase=0.02 , __lowerCAmelCase=3 , __lowerCAmelCase=4 , __lowerCAmelCase=None , ): """simple docstring""" __magic_name__ :Optional[int] = parent __magic_name__ :List[Any] = 1_3 __magic_name__ :Union[str, Any] = 7 __magic_name__ :Optional[Any] = True __magic_name__ :Tuple = True __magic_name__ :List[str] = True __magic_name__ :List[Any] = True __magic_name__ :int = 9_9 __magic_name__ :Any = 3_2 __magic_name__ :Union[str, Any] = 2 __magic_name__ :List[str] = 4 __magic_name__ :List[Any] = 3_7 __magic_name__ :Tuple = '''gelu''' __magic_name__ :Any = 0.1 __magic_name__ :str = 0.1 __magic_name__ :List[str] = 5_1_2 __magic_name__ :int = 1_6 __magic_name__ :Any = 2 __magic_name__ :List[Any] = 0.02 __magic_name__ :Optional[Any] = 3 __magic_name__ :Tuple = 4 __magic_name__ :Optional[Any] = None def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ :str = None if self.use_input_mask: __magic_name__ :Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ :str = None if self.use_token_type_ids: __magic_name__ :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ :Union[str, Any] = None __magic_name__ :Tuple = None __magic_name__ :str = None if self.use_labels: __magic_name__ :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ :List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ :str = 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=__lowerCAmelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :int = TFRoFormerModel(config=__lowerCAmelCase ) __magic_name__ :Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __magic_name__ :List[str] = [input_ids, input_mask] __magic_name__ :Any = model(__lowerCAmelCase ) __magic_name__ :List[str] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Dict = True __magic_name__ :List[str] = TFRoFormerForCausalLM(config=__lowerCAmelCase ) __magic_name__ :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Optional[Any] = model(__lowerCAmelCase )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = TFRoFormerForMaskedLM(config=__lowerCAmelCase ) __magic_name__ :Any = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :int = self.num_labels __magic_name__ :str = TFRoFormerForSequenceClassification(config=__lowerCAmelCase ) __magic_name__ :Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :str = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Union[str, Any] = self.num_choices __magic_name__ :Tuple = TFRoFormerForMultipleChoice(config=__lowerCAmelCase ) __magic_name__ :int = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :Optional[Any] = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :Union[str, Any] = tf.tile(tf.expand_dims(__lowerCAmelCase , 1 ) , (1, self.num_choices, 1) ) __magic_name__ :str = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __magic_name__ :Tuple = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[int] = self.num_labels __magic_name__ :Any = TFRoFormerForTokenClassification(config=__lowerCAmelCase ) __magic_name__ :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :List[str] = TFRoFormerForQuestionAnswering(config=__lowerCAmelCase ) __magic_name__ :List[str] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __magic_name__ :Union[str, Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) :Union[str, Any] = config_and_inputs __magic_name__ :Optional[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCamelCase_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): a__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) a__ = ( { '''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 {} ) a__ = False a__ = False def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def A ( self ): """simple docstring""" __magic_name__ :List[str] = TFRoFormerModelTester(self ) __magic_name__ :List[str] = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def A ( self ): """simple docstring""" self.config_tester.run_common_tests() def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase ) @slow def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(__lowerCAmelCase ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): @slow def A ( self ): """simple docstring""" __magic_name__ :int = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __magic_name__ :Dict = tf.constant([[0, 1, 2, 3, 4, 5]] ) __magic_name__ :Optional[Any] = model(__lowerCAmelCase )[0] # TODO Replace vocab size __magic_name__ :int = 5_0_0_0_0 __magic_name__ :Tuple = [1, 6, vocab_size] self.assertEqual(output.shape , __lowerCAmelCase ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. __magic_name__ :Any = 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] , __lowerCAmelCase , atol=1E-4 ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): a__ = 1e-4 def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = tf.constant([[4, 1_0]] ) __magic_name__ :Optional[int] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) __magic_name__ :Optional[Any] = emba(input_ids.shape ) __magic_name__ :List[str] = 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(__lowerCAmelCase , __lowerCAmelCase , atol=self.tolerance ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = 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], ] ) __magic_name__ :Union[str, Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) __magic_name__ :Optional[int] = emba.weight[:3, :5] tf.debugging.assert_near(__lowerCAmelCase , __lowerCAmelCase , atol=self.tolerance ) @require_tf class lowerCamelCase_ ( unittest.TestCase ): a__ = 1e-4 def A ( self ): """simple docstring""" # 2,12,16,64 __magic_name__ :int = tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __magic_name__ :str = -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __magic_name__ :int = TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) __magic_name__ :List[str] = embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] __magic_name__ , __magic_name__ :Union[str, Any] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :Tuple = 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], ] ) __magic_name__ :List[str] = 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] , __lowerCAmelCase , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , __lowerCAmelCase , atol=self.tolerance )
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class lowerCamelCase_ ( lowerCamelCase ): a__ = '''luke''' def __init__( self , __lowerCAmelCase=5_0_2_6_7 , __lowerCAmelCase=5_0_0_0_0_0 , __lowerCAmelCase=7_6_8 , __lowerCAmelCase=2_5_6 , __lowerCAmelCase=1_2 , __lowerCAmelCase=1_2 , __lowerCAmelCase=3_0_7_2 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=5_1_2 , __lowerCAmelCase=2 , __lowerCAmelCase=0.02 , __lowerCAmelCase=1E-12 , __lowerCAmelCase=True , __lowerCAmelCase=None , __lowerCAmelCase=1 , __lowerCAmelCase=0 , __lowerCAmelCase=2 , **__lowerCAmelCase , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :List[str] = vocab_size __magic_name__ :int = entity_vocab_size __magic_name__ :List[str] = hidden_size __magic_name__ :Union[str, Any] = entity_emb_size __magic_name__ :Tuple = num_hidden_layers __magic_name__ :Dict = num_attention_heads __magic_name__ :Optional[Any] = hidden_act __magic_name__ :Tuple = intermediate_size __magic_name__ :List[Any] = hidden_dropout_prob __magic_name__ :List[Any] = attention_probs_dropout_prob __magic_name__ :Dict = max_position_embeddings __magic_name__ :Optional[Any] = type_vocab_size __magic_name__ :int = initializer_range __magic_name__ :str = layer_norm_eps __magic_name__ :Union[str, Any] = use_entity_aware_attention __magic_name__ :Tuple = classifier_dropout
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available SCREAMING_SNAKE_CASE__ : Optional[int] = {"""tokenization_herbert""": ["""HerbertTokenizer"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = ["""HerbertTokenizerFast"""] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
0
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Any = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
0
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :str = XCLIPTextConfig() # derive patch size from model name __magic_name__ :Union[str, Any] = model_name.find('''patch''' ) __magic_name__ :Optional[Any] = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] ) __magic_name__ :int = XCLIPVisionConfig(patch_size=snake_case, num_frames=snake_case ) if "large" in model_name: __magic_name__ :Dict = 7_6_8 __magic_name__ :int = 3_0_7_2 __magic_name__ :List[Any] = 1_2 __magic_name__ :str = 1_0_2_4 __magic_name__ :Any = 4_0_9_6 __magic_name__ :Optional[Any] = 1_6 __magic_name__ :Union[str, Any] = 2_4 __magic_name__ :Union[str, Any] = 7_6_8 __magic_name__ :Tuple = 3_0_7_2 if model_name == "xclip-large-patch14-16-frames": __magic_name__ :List[str] = 3_3_6 __magic_name__ :Any = XCLIPConfig.from_text_vision_configs(snake_case, snake_case ) if "large" in model_name: __magic_name__ :str = 7_6_8 return config def __lowercase ( snake_case ): """simple docstring""" if name == "token_embedding.weight": __magic_name__ :Any = name.replace('''token_embedding.weight''', '''text_model.embeddings.token_embedding.weight''' ) if name == "positional_embedding": __magic_name__ :Any = name.replace('''positional_embedding''', '''text_model.embeddings.position_embedding.weight''' ) if "ln_1" in name: __magic_name__ :List[str] = name.replace('''ln_1''', '''layer_norm1''' ) if "ln_2" in name: __magic_name__ :str = name.replace('''ln_2''', '''layer_norm2''' ) if "c_fc" in name: __magic_name__ :List[Any] = name.replace('''c_fc''', '''fc1''' ) if "c_proj" in name: __magic_name__ :Any = name.replace('''c_proj''', '''fc2''' ) if name.startswith('''transformer.resblocks''' ): __magic_name__ :Any = name.replace('''transformer.resblocks''', '''text_model.encoder.layers''' ) if "attn.out_proj" in name and "message" not in name: __magic_name__ :Union[str, Any] = name.replace('''attn.out_proj''', '''self_attn.out_proj''' ) if "ln_final" in name: __magic_name__ :Tuple = name.replace('''ln_final''', '''text_model.final_layer_norm''' ) # visual encoder if name == "visual.class_embedding": __magic_name__ :List[Any] = name.replace('''visual.class_embedding''', '''vision_model.embeddings.class_embedding''' ) if name == "visual.positional_embedding": __magic_name__ :Any = name.replace('''visual.positional_embedding''', '''vision_model.embeddings.position_embedding.weight''' ) if name.startswith('''visual.transformer.resblocks''' ): __magic_name__ :Union[str, Any] = name.replace('''visual.transformer.resblocks''', '''vision_model.encoder.layers''' ) if "visual.conv1" in name: __magic_name__ :Tuple = name.replace('''visual.conv1''', '''vision_model.embeddings.patch_embedding''' ) if "visual.ln_pre" in name: __magic_name__ :Tuple = name.replace('''visual.ln_pre''', '''vision_model.pre_layernorm''' ) if "visual.ln_post" in name: __magic_name__ :Optional[Any] = name.replace('''visual.ln_post''', '''vision_model.post_layernorm''' ) if "visual.proj" in name: __magic_name__ :Tuple = name.replace('''visual.proj''', '''visual_projection.weight''' ) if "text_projection" in name: __magic_name__ :int = name.replace('''text_projection''', '''text_projection.weight''' ) # things on top if "prompts_visual_proj" in name: __magic_name__ :int = name.replace('''prompts_visual_proj''', '''prompts_visual_projection''' ) if "prompts_visual_ln" in name: __magic_name__ :Dict = name.replace('''prompts_visual_ln''', '''prompts_visual_layernorm''' ) # mit if name == "mit.positional_embedding": __magic_name__ :List[Any] = name.replace('''positional''', '''position''' ) if name.startswith('''mit.resblocks''' ): __magic_name__ :Union[str, Any] = name.replace('''mit.resblocks''', '''mit.encoder.layers''' ) # prompts generator if name.startswith('''prompts_generator.norm''' ): __magic_name__ :str = name.replace('''prompts_generator.norm''', '''prompts_generator.layernorm''' ) return name def __lowercase ( snake_case, snake_case ): """simple docstring""" for key in orig_state_dict.copy().keys(): __magic_name__ :Any = orig_state_dict.pop(snake_case ) if "attn.in_proj" in key: __magic_name__ :str = key.split('''.''' ) if key.startswith('''visual''' ): __magic_name__ :List[Any] = key_split[3] __magic_name__ :List[Any] = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __magic_name__ :List[Any] = val[ :dim, : ] __magic_name__ :List[str] = val[ dim : dim * 2, : ] __magic_name__ :List[str] = val[ -dim:, : ] else: __magic_name__ :str = val[ :dim ] __magic_name__ :Optional[int] = val[ dim : dim * 2 ] __magic_name__ :Any = val[ -dim: ] else: if "weight" in key: __magic_name__ :int = val[ :dim, : ] __magic_name__ :Union[str, Any] = val[ dim : dim * 2, : ] __magic_name__ :List[Any] = val[ -dim:, : ] else: __magic_name__ :Union[str, Any] = val[:dim] __magic_name__ :str = val[ dim : dim * 2 ] __magic_name__ :Dict = val[-dim:] elif key.startswith('''mit''' ): __magic_name__ :List[Any] = key_split[2] __magic_name__ :Any = config.vision_config.mit_hidden_size if "weight" in key: __magic_name__ :Union[str, Any] = val[:dim, :] __magic_name__ :Optional[int] = val[dim : dim * 2, :] __magic_name__ :int = val[-dim:, :] else: __magic_name__ :Tuple = val[:dim] __magic_name__ :Optional[int] = val[dim : dim * 2] __magic_name__ :Optional[int] = val[-dim:] else: __magic_name__ :Any = key_split[2] __magic_name__ :List[Any] = config.text_config.hidden_size if "weight" in key: __magic_name__ :Union[str, Any] = val[:dim, :] __magic_name__ :Tuple = val[ dim : dim * 2, : ] __magic_name__ :str = val[-dim:, :] else: __magic_name__ :int = val[:dim] __magic_name__ :Any = val[ dim : dim * 2 ] __magic_name__ :str = val[-dim:] else: __magic_name__ :Tuple = rename_key(snake_case ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __magic_name__ :List[Any] = val.T __magic_name__ :Optional[Any] = val return orig_state_dict def __lowercase ( snake_case ): """simple docstring""" if num_frames == 8: __magic_name__ :Any = '''eating_spaghetti_8_frames.npy''' elif num_frames == 1_6: __magic_name__ :List[Any] = '''eating_spaghetti.npy''' elif num_frames == 3_2: __magic_name__ :Tuple = '''eating_spaghetti_32_frames.npy''' __magic_name__ :str = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename=snake_case, repo_type='''dataset''', ) __magic_name__ :List[Any] = np.load(snake_case ) return list(snake_case ) def __lowercase ( snake_case, snake_case=None, snake_case=False ): """simple docstring""" __magic_name__ :Union[str, Any] = { # fully supervised kinetics-400 checkpoints '''xclip-base-patch32''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth''', '''xclip-base-patch32-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth''' ), '''xclip-base-patch16''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth''', '''xclip-base-patch16-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth''' ), '''xclip-large-patch14''': '''https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb''', '''xclip-large-patch14-16-frames''': '''https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f''', # fully supervised kinetics-600 checkpoints '''xclip-base-patch16-kinetics-600''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth''' ), '''xclip-base-patch16-kinetics-600-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth''' ), '''xclip-large-patch14-kinetics-600''': '''https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be''', # few shot '''xclip-base-patch16-hmdb-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth''' ), '''xclip-base-patch16-hmdb-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth''' ), '''xclip-base-patch16-hmdb-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth''' ), '''xclip-base-patch16-hmdb-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth''' ), '''xclip-base-patch16-ucf-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth''' ), '''xclip-base-patch16-ucf-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth''' ), '''xclip-base-patch16-ucf-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth''' ), '''xclip-base-patch16-ucf-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth''' ), # zero shot '''xclip-base-patch16-zero-shot''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth''', } __magic_name__ :Optional[int] = model_to_url[model_name] __magic_name__ :List[str] = 8 if "16-frames" in model_name: __magic_name__ :List[Any] = 1_6 elif "shot" in model_name: __magic_name__ :Dict = 3_2 __magic_name__ :str = get_xclip_config(snake_case, snake_case ) __magic_name__ :List[Any] = XCLIPModel(snake_case ) model.eval() if "drive" in checkpoint_url: __magic_name__ :Any = '''pytorch_model.bin''' gdown.cached_download(snake_case, snake_case, quiet=snake_case ) __magic_name__ :Optional[Any] = torch.load(snake_case, map_location='''cpu''' )['''model'''] else: __magic_name__ :Optional[int] = torch.hub.load_state_dict_from_url(snake_case )['''model'''] __magic_name__ :List[str] = convert_state_dict(snake_case, snake_case ) __magic_name__ :List[Any] = XCLIPModel(snake_case ) __magic_name__ , __magic_name__ :Optional[Any] = model.load_state_dict(snake_case, strict=snake_case ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __magic_name__ :str = 3_3_6 if model_name == '''xclip-large-patch14-16-frames''' else 2_2_4 __magic_name__ :Optional[int] = VideoMAEImageProcessor(size=snake_case ) __magic_name__ :Optional[int] = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ) __magic_name__ :Tuple = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' ) __magic_name__ :Optional[int] = XCLIPProcessor(image_processor=snake_case, tokenizer=snake_case ) __magic_name__ :List[Any] = prepare_video(snake_case ) __magic_name__ :str = processor( text=['''playing sports''', '''eating spaghetti''', '''go shopping'''], videos=snake_case, return_tensors='''pt''', padding=snake_case ) print('''Shape of pixel values:''', inputs.pixel_values.shape ) with torch.no_grad(): __magic_name__ :Tuple = model(**snake_case ) # Verify outputs __magic_name__ :Any = outputs.logits_per_video __magic_name__ :str = logits_per_video.softmax(dim=1 ) print('''Probs:''', snake_case ) # kinetics-400 if model_name == "xclip-base-patch32": __magic_name__ :Dict = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": __magic_name__ :str = torch.tensor([[7.0_9_9_9E-0_4, 9.9_8_8_3E-0_1, 4.5_5_8_0E-0_4]] ) elif model_name == "xclip-base-patch16": __magic_name__ :Tuple = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": __magic_name__ :Tuple = torch.tensor([[7.6_9_3_7E-0_4, 9.9_7_2_8E-0_1, 1.9_4_7_3E-0_3]] ) elif model_name == "xclip-large-patch14": __magic_name__ :str = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": __magic_name__ :Optional[int] = torch.tensor([[3.3_8_7_7E-0_4, 9.9_9_3_7E-0_1, 2.8_8_8_8E-0_4]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __magic_name__ :Optional[int] = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __magic_name__ :List[str] = torch.tensor([[3.8_5_5_4E-0_4, 9.9_9_2_9E-0_1, 3.2_7_5_4E-0_4]] ) elif model_name == "xclip-large-patch14-kinetics-600": __magic_name__ :List[str] = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __magic_name__ :Tuple = torch.tensor([[7.1_8_9_0E-0_6, 9.9_9_9_4E-0_1, 5.6_5_5_9E-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __magic_name__ :List[str] = torch.tensor([[1.0_3_2_0E-0_5, 9.9_9_9_3E-0_1, 6.2_4_3_5E-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __magic_name__ :Optional[int] = torch.tensor([[4.1_3_7_7E-0_6, 9.9_9_9_0E-0_1, 9.8_3_8_6E-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __magic_name__ :Optional[int] = torch.tensor([[4.1_3_4_7E-0_5, 9.9_9_6_2E-0_1, 3.3_4_1_1E-0_4]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __magic_name__ :Union[str, Any] = torch.tensor([[8.5_8_5_7E-0_5, 9.9_9_2_8E-0_1, 6.3_2_9_1E-0_4]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __magic_name__ :Union[str, Any] = torch.tensor([[8.5_8_5_7E-0_5, 9.9_9_2_8E-0_1, 6.3_2_9_1E-0_4]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __magic_name__ :Optional[int] = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __magic_name__ :Any = torch.tensor([[9.8_2_1_9E-0_4, 9.9_5_9_3E-0_1, 3.0_8_6_3E-0_3]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __magic_name__ :Optional[int] = torch.tensor([[3.5_0_8_2E-0_4, 9.9_7_8_5E-0_1, 1.7_9_6_6E-0_3]] ) else: raise ValueError(f'''Model name {model_name} not supported''' ) assert torch.allclose(snake_case, snake_case, atol=1E-3 ) 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(snake_case ) if push_to_hub: print('''Pushing model, processor and slow tokenizer files to the hub...''' ) model.push_to_hub(snake_case, organization='''nielsr''' ) processor.push_to_hub(snake_case, organization='''nielsr''' ) slow_tokenizer.push_to_hub(snake_case, organization='''nielsr''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""xclip-base-patch32""", type=str, help="""Name of the model.""", ) 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.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
0
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): SCREAMING_SNAKE_CASE__ : Dict = """pt""" elif is_tf_available(): SCREAMING_SNAKE_CASE__ : List[str] = """tf""" else: SCREAMING_SNAKE_CASE__ : List[Any] = """jax""" class lowerCamelCase_ ( lowerCamelCase , unittest.TestCase ): a__ = PerceiverTokenizer a__ = False def A ( self ): """simple docstring""" super().setUp() __magic_name__ :str = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self ): """simple docstring""" return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def A ( self , **__lowerCAmelCase ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def A ( self , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=2_0 , __lowerCAmelCase=5 ): """simple docstring""" # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __magic_name__ :List[str] = [] for i in range(len(__lowerCAmelCase ) ): try: __magic_name__ :Optional[int] = tokenizer.decode([i] , clean_up_tokenization_spaces=__lowerCAmelCase ) except UnicodeDecodeError: pass toks.append((i, tok) ) __magic_name__ :Dict = list(filter(lambda __lowerCAmelCase : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , __lowerCAmelCase ) ) __magic_name__ :Union[str, Any] = list(filter(lambda __lowerCAmelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=__lowerCAmelCase ) , __lowerCAmelCase ) ) if max_length is not None and len(__lowerCAmelCase ) > max_length: __magic_name__ :int = toks[:max_length] if min_length is not None and len(__lowerCAmelCase ) < min_length and len(__lowerCAmelCase ) > 0: while len(__lowerCAmelCase ) < min_length: __magic_name__ :str = toks + toks # toks_str = [t[1] for t in toks] __magic_name__ :Dict = [t[0] for t in toks] # Ensure consistency __magic_name__ :List[str] = tokenizer.decode(__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) if " " not in output_txt and len(__lowerCAmelCase ) > 1: __magic_name__ :Tuple = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__lowerCAmelCase ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__lowerCAmelCase ) ) if with_prefix_space: __magic_name__ :Union[str, Any] = ''' ''' + output_txt __magic_name__ :str = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) return output_txt, output_ids def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = self.perceiver_tokenizer __magic_name__ :List[Any] = '''Unicode €.''' __magic_name__ :Tuple = tokenizer(__lowerCAmelCase ) __magic_name__ :Optional[int] = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5] self.assertEqual(encoded['''input_ids'''] , __lowerCAmelCase ) # decoding __magic_name__ :List[str] = tokenizer.decode(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , '''[CLS]Unicode €.[SEP]''' ) __magic_name__ :int = tokenizer('''e è é ê ë''' ) __magic_name__ :List[Any] = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5] self.assertEqual(encoded['''input_ids'''] , __lowerCAmelCase ) # decoding __magic_name__ :Tuple = tokenizer.decode(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def A ( self ): """simple docstring""" __magic_name__ :Tuple = self.perceiver_tokenizer __magic_name__ :Tuple = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off __magic_name__ :Union[str, Any] = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0] # fmt: on __magic_name__ :List[str] = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) if FRAMEWORK != "jax": __magic_name__ :List[Any] = list(batch.input_ids.numpy()[0] ) else: __magic_name__ :Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual((2, 3_8) , batch.input_ids.shape ) self.assertEqual((2, 3_8) , batch.attention_mask.shape ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.perceiver_tokenizer __magic_name__ :Dict = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __magic_name__ :Any = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , __lowerCAmelCase ) self.assertIn('''attention_mask''' , __lowerCAmelCase ) self.assertNotIn('''decoder_input_ids''' , __lowerCAmelCase ) self.assertNotIn('''decoder_attention_mask''' , __lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :str = self.perceiver_tokenizer __magic_name__ :Optional[Any] = [ '''Summary of the text.''', '''Another summary.''', ] __magic_name__ :int = tokenizer( text_target=__lowerCAmelCase , max_length=3_2 , padding='''max_length''' , truncation=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) self.assertEqual(3_2 , targets['''input_ids'''].shape[1] ) def A ( self ): """simple docstring""" # safety check on max_len default value so we are sure the test works __magic_name__ :List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test __magic_name__ :Dict = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ :Union[str, Any] = tempfile.mkdtemp() __magic_name__ :Union[str, Any] = ''' He is very happy, UNwant\u00E9d,running''' __magic_name__ :Optional[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) tokenizer.save_pretrained(__lowerCAmelCase ) __magic_name__ :int = tokenizer.__class__.from_pretrained(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = after_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) shutil.rmtree(__lowerCAmelCase ) __magic_name__ :int = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ :Union[str, Any] = tempfile.mkdtemp() __magic_name__ :Tuple = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) __magic_name__ :Optional[Any] = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) __magic_name__ :List[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) tokenizer.save_pretrained(__lowerCAmelCase ) __magic_name__ :int = tokenizer.__class__.from_pretrained(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = after_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) __magic_name__ :Optional[Any] = tokenizer.__class__.from_pretrained(__lowerCAmelCase , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :str = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: __magic_name__ :Union[str, Any] = json.load(__lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: __magic_name__ :Tuple = json.load(__lowerCAmelCase ) __magic_name__ :str = [F'''<extra_id_{i}>''' for i in range(1_2_5 )] __magic_name__ :List[str] = added_tokens_extra_ids + [ '''an_additional_special_token''' ] __magic_name__ :Tuple = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(__lowerCAmelCase , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__lowerCAmelCase , __lowerCAmelCase ) with open(os.path.join(__lowerCAmelCase , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__lowerCAmelCase , __lowerCAmelCase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __magic_name__ :Optional[int] = tokenizer_class.from_pretrained( __lowerCAmelCase , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __magic_name__ :Optional[Any] = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=__lowerCAmelCase )] __magic_name__ :Any = tokenizer_class.from_pretrained( __lowerCAmelCase , additional_special_tokens=__lowerCAmelCase , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def A ( self ): """simple docstring""" __magic_name__ :List[str] = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_7_8] ) , '''�''' ) def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens __magic_name__ :List[Any] = self.get_tokenizers(fast=__lowerCAmelCase , do_lower_case=__lowerCAmelCase ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __magic_name__ :Any = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] __magic_name__ :Union[str, Any] = tokenizer.convert_tokens_to_string(__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase )
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowerCamelCase_ ( lowerCamelCase ): def __init__( self , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[int] = params __magic_name__ :Any = np.array(__lowerCAmelCase ) __magic_name__ :Optional[Any] = np.array([len(__lowerCAmelCase ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , __lowerCAmelCase ): """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self ): """simple docstring""" return len(self.lengths ) def A ( self ): """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def A ( self ): """simple docstring""" __magic_name__ :Any = self.params.max_model_input_size __magic_name__ :int = self.lengths > max_len logger.info(F'''Splitting {sum(__lowerCAmelCase )} too long sequences.''' ) def divide_chunks(__lowerCAmelCase , __lowerCAmelCase ): return [l[i : i + n] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase )] __magic_name__ :Optional[int] = [] __magic_name__ :List[Any] = [] if self.params.mlm: __magic_name__ , __magic_name__ :Optional[Any] = self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token'''] else: __magic_name__ , __magic_name__ :Tuple = self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token'''] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: __magic_name__ :int = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __magic_name__ :List[Any] = np.insert(__lowerCAmelCase , 0 , __lowerCAmelCase ) if sub_s[-1] != sep_id: __magic_name__ :Union[str, Any] = np.insert(__lowerCAmelCase , len(__lowerCAmelCase ) , __lowerCAmelCase ) assert len(__lowerCAmelCase ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__lowerCAmelCase ) new_tok_ids.extend(__lowerCAmelCase ) new_lengths.extend([len(__lowerCAmelCase ) for l in sub_seqs] ) __magic_name__ :Tuple = np.array(__lowerCAmelCase ) __magic_name__ :Optional[int] = np.array(__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = len(self ) __magic_name__ :int = self.lengths > 1_1 __magic_name__ :List[str] = self.token_ids[indices] __magic_name__ :Union[str, Any] = self.lengths[indices] __magic_name__ :List[str] = len(self ) logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def A ( self ): """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: __magic_name__ :Tuple = self.params.special_tok_ids['''unk_token'''] __magic_name__ :Dict = len(self ) __magic_name__ :Tuple = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __magic_name__ :int = (unk_occs / self.lengths) < 0.5 __magic_name__ :str = self.token_ids[indices] __magic_name__ :str = self.lengths[indices] __magic_name__ :Any = len(self ) logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def A ( self ): """simple docstring""" if not self.params.is_master: return logger.info(F'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = [t[0] for t in batch] __magic_name__ :List[Any] = [t[1] for t in batch] assert len(__lowerCAmelCase ) == len(__lowerCAmelCase ) # Max for paddings __magic_name__ :Tuple = max(__lowerCAmelCase ) # Pad token ids if self.params.mlm: __magic_name__ :Any = self.params.special_tok_ids['''pad_token'''] else: __magic_name__ :str = self.params.special_tok_ids['''unk_token'''] __magic_name__ :Any = [list(t.astype(__lowerCAmelCase ) ) + [pad_idx] * (max_seq_len_ - len(__lowerCAmelCase )) for t in token_ids] assert len(tk_ ) == len(__lowerCAmelCase ) assert all(len(__lowerCAmelCase ) == max_seq_len_ for t in tk_ ) __magic_name__ :Optional[int] = torch.tensor(tk_ ) # (bs, max_seq_len_) __magic_name__ :Optional[int] = torch.tensor(__lowerCAmelCase ) # (bs) return tk_t, lg_t
0
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = """▁""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""vocab_file""": """spiece.model"""} SCREAMING_SNAKE_CASE__ : List[Any] = { """vocab_file""": { """google/reformer-crime-and-punishment""": ( """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model""" ) } } SCREAMING_SNAKE_CASE__ : Optional[int] = { """google/reformer-crime-and-punishment""": 52_42_88, } class lowerCamelCase_ ( lowerCamelCase ): a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = ['''input_ids''', '''attention_mask'''] def __init__( self , __lowerCAmelCase , __lowerCAmelCase="</s>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase=[] , __lowerCAmelCase = None , **__lowerCAmelCase , ): """simple docstring""" __magic_name__ :int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , additional_special_tokens=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) __magic_name__ :Optional[Any] = vocab_file __magic_name__ :int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCAmelCase ) @property def A ( self ): """simple docstring""" return self.sp_model.get_piece_size() def A ( self ): """simple docstring""" __magic_name__ :str = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.__dict__.copy() __magic_name__ :Optional[Any] = None return state def __setstate__( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __magic_name__ :Optional[int] = {} __magic_name__ :Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A ( self , __lowerCAmelCase ): """simple docstring""" return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def A ( self , __lowerCAmelCase ): """simple docstring""" return self.sp_model.piece_to_id(__lowerCAmelCase ) def A ( self , __lowerCAmelCase ): """simple docstring""" if index < self.sp_model.get_piece_size(): __magic_name__ :int = self.sp_model.IdToPiece(__lowerCAmelCase ) return token def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = [] __magic_name__ :Tuple = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__lowerCAmelCase ) + token __magic_name__ :Optional[Any] = [] else: current_sub_tokens.append(__lowerCAmelCase ) out_string += self.sp_model.decode(__lowerCAmelCase ) return out_string.strip() def A ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" if not os.path.isdir(__lowerCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ :Optional[int] = os.path.join( __lowerCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCAmelCase , '''wb''' ) as fi: __magic_name__ :Dict = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (out_vocab_file,)
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = """▁""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""vocab_file""": """spiece.model"""} SCREAMING_SNAKE_CASE__ : List[Any] = { """vocab_file""": { """google/reformer-crime-and-punishment""": ( """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model""" ) } } SCREAMING_SNAKE_CASE__ : Optional[int] = { """google/reformer-crime-and-punishment""": 52_42_88, } class lowerCamelCase_ ( lowerCamelCase ): a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = ['''input_ids''', '''attention_mask'''] def __init__( self , __lowerCAmelCase , __lowerCAmelCase="</s>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase=[] , __lowerCAmelCase = None , **__lowerCAmelCase , ): """simple docstring""" __magic_name__ :int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , additional_special_tokens=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) __magic_name__ :Optional[Any] = vocab_file __magic_name__ :int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCAmelCase ) @property def A ( self ): """simple docstring""" return self.sp_model.get_piece_size() def A ( self ): """simple docstring""" __magic_name__ :str = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" __magic_name__ :Optional[Any] = self.__dict__.copy() __magic_name__ :Optional[Any] = None return state def __setstate__( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __magic_name__ :Optional[int] = {} __magic_name__ :Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A ( self , __lowerCAmelCase ): """simple docstring""" return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def A ( self , __lowerCAmelCase ): """simple docstring""" return self.sp_model.piece_to_id(__lowerCAmelCase ) def A ( self , __lowerCAmelCase ): """simple docstring""" if index < self.sp_model.get_piece_size(): __magic_name__ :int = self.sp_model.IdToPiece(__lowerCAmelCase ) return token def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = [] __magic_name__ :Tuple = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__lowerCAmelCase ) + token __magic_name__ :Optional[Any] = [] else: current_sub_tokens.append(__lowerCAmelCase ) out_string += self.sp_model.decode(__lowerCAmelCase ) return out_string.strip() def A ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" if not os.path.isdir(__lowerCAmelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ :Optional[int] = os.path.join( __lowerCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCAmelCase , '''wb''' ) as fi: __magic_name__ :Dict = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (out_vocab_file,)
0
1
import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) class lowerCamelCase_ ( lowerCamelCase ): def __init__( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" warnings.warn( '''The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DPTImageProcessor instead.''' , __lowerCAmelCase , ) super().__init__(*__lowerCAmelCase , **__lowerCAmelCase )
0
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowerCamelCase_ ( lowerCamelCase , unittest.TestCase ): a__ = MobileBertTokenizer a__ = MobileBertTokenizerFast a__ = True a__ = True a__ = filter_non_english a__ = '''google/mobilebert-uncased''' def A ( self ): """simple docstring""" super().setUp() __magic_name__ :Tuple = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __magic_name__ :Dict = 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] ) ) __magic_name__ :List[str] = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Union[str, Any] = '''UNwant\u00E9d,running''' __magic_name__ :int = '''unwanted, running''' return input_text, output_text def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = self.tokenizer_class(self.vocab_file ) __magic_name__ :List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__lowerCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def A ( self ): """simple docstring""" if not self.test_rust_tokenizer: return __magic_name__ :int = self.get_tokenizer() __magic_name__ :Tuple = self.get_rust_tokenizer() __magic_name__ :List[str] = '''UNwant\u00E9d,running''' __magic_name__ :Optional[Any] = tokenizer.tokenize(__lowerCAmelCase ) __magic_name__ :List[Any] = rust_tokenizer.tokenize(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :int = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :str = rust_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :List[Any] = self.get_rust_tokenizer() __magic_name__ :Any = tokenizer.encode(__lowerCAmelCase ) __magic_name__ :Any = rust_tokenizer.encode(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) # With lower casing __magic_name__ :Any = self.get_tokenizer(do_lower_case=__lowerCAmelCase ) __magic_name__ :List[Any] = self.get_rust_tokenizer(do_lower_case=__lowerCAmelCase ) __magic_name__ :Dict = '''UNwant\u00E9d,running''' __magic_name__ :Tuple = tokenizer.tokenize(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = rust_tokenizer.tokenize(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :Optional[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :Dict = rust_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :Tuple = self.get_rust_tokenizer() __magic_name__ :Dict = tokenizer.encode(__lowerCAmelCase ) __magic_name__ :List[Any] = rust_tokenizer.encode(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def A ( self ): """simple docstring""" __magic_name__ :List[Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def A ( self ): """simple docstring""" __magic_name__ :Dict = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self ): """simple docstring""" __magic_name__ :List[str] = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self ): """simple docstring""" __magic_name__ :int = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def A ( self ): """simple docstring""" __magic_name__ :int = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] __magic_name__ :Union[str, Any] = {} for i, token in enumerate(__lowerCAmelCase ): __magic_name__ :Tuple = i __magic_name__ :List[Any] = WordpieceTokenizer(vocab=__lowerCAmelCase , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def A ( self ): """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def A ( self ): """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def A ( self ): """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def A ( self ): """simple docstring""" __magic_name__ :Any = self.get_tokenizer() __magic_name__ :Any = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__lowerCAmelCase ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__lowerCAmelCase ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def A ( self ): """simple docstring""" __magic_name__ :Optional[int] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) __magic_name__ :Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=__lowerCAmelCase ) __magic_name__ :List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__lowerCAmelCase ) __magic_name__ :Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase ) __magic_name__ :List[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase , __lowerCAmelCase ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def A ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __magic_name__ :Optional[Any] = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :Optional[int] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __magic_name__ :Optional[Any] = tokenizer_r.encode_plus( __lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , ) __magic_name__ :Any = tokenizer_r.do_lower_case if hasattr(__lowerCAmelCase , '''do_lower_case''' ) else False __magic_name__ :Optional[int] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''Allen'''), ((2_1, 2_3), '''##NL'''), ((2_3, 2_4), '''##P'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''allen'''), ((2_1, 2_3), '''##nl'''), ((2_3, 2_4), '''##p'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def A ( self ): """simple docstring""" __magic_name__ :Dict = ['''的''', '''人''', '''有'''] __magic_name__ :Any = ''''''.join(__lowerCAmelCase ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __magic_name__ :Optional[Any] = True __magic_name__ :Optional[int] = self.tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :Tuple = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :Dict = tokenizer_p.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :List[str] = tokenizer_r.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :Dict = tokenizer_r.convert_ids_to_tokens(__lowerCAmelCase ) __magic_name__ :Union[str, Any] = tokenizer_p.convert_ids_to_tokens(__lowerCAmelCase ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) __magic_name__ :List[str] = False __magic_name__ :Tuple = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :List[str] = self.tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase ) __magic_name__ :Optional[Any] = tokenizer_r.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :Union[str, Any] = tokenizer_p.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) __magic_name__ :List[str] = tokenizer_r.convert_ids_to_tokens(__lowerCAmelCase ) __magic_name__ :Optional[int] = tokenizer_p.convert_ids_to_tokens(__lowerCAmelCase ) # it is expected that only the first Chinese character is not preceded by "##". __magic_name__ :Dict = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__lowerCAmelCase ) ] self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
0
1

Dataset Card for "python_codestyles-random-1k"

This dataset contains negative and positive examples with python code of compliance with a code style. A positive example represents compliance with the code style (label is 1). Each example is composed of two components, the first component consists of a code that either conforms to the code style or violates it and the second component corresponding to an example code that already conforms to a code style. In total, the dataset contains 1.000 completely different code styles. The code styles differ in at least one codestyle rule, which is called a random codestyle dataset variant. The dataset consists of a training and test group, with none of the code styles overlapping between groups. In addition, both groups contain completely different underlying codes.

The examples contain source code from the following repositories:

repository tag or commit
TheAlgorithms/Python f614ed72170011d2d439f7901e1c8daa7deac8c4
huggingface/transformers v4.31.0
huggingface/datasets 2.13.1
huggingface/diffusers v0.18.2
huggingface/accelerate v0.21.0

You can find the corresponding code styles of the examples in the file additional_data.json. The code styles in the file are split by training and test group and the index corresponds to the class for the columns code_codestyle and style_context_codestyle in the dataset.

There are 364.400 samples in total and 182.200 positive and 182.200 negative samples.

Downloads last month
94
Edit dataset card

Models trained or fine-tuned on infinityofspace/python_codestyles-random-1k